I've setup a jQuery add/update/delete table which uses ajax calls to controller. Some of the data fields are null.
Is there a way to write this JavaScript code to show empty value if database value returned is null?
Here's the ajax call to the controller, with the data returned to complete the table.
let html = '' +
'<tr>'+
'<td class="fw-normal">'+data.id+'</td>'+
'<td class="fw-normal">'+data.employment_type+'</td>'+
'<td class="fw-normal">'+data.start_date+'</td>'+
'<td class="fw-normal">'+data.end_date+'</td>'+
'<td class="fw-normal">'+data.state+'</td>'+
'<td class="fw-normal">'+data.city+'</td>'+
'<td>'+
'<form action="'+data.delete_url+'" method="post">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'ویرایش'+
'<button type="submit" class="btn btn-danger btn-sm job-destroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>';
$('#showJobs').append(html);
Note: I want to did not show ward of null.
Consider the following example code.
function checkNull(string) {
if (string === null) {
string = ""
}
return string;
}
function addRow(data) {
var row = $("<tr>");
$.each(data, function(key, value) {
if (key != "delete_url" || key != "edit_url") {
$("<td>", {
class: "fw-normal"
}).html(checkNull(value)).appendTo(row);
}
});
$("<td>").appendTo(row);
$("<form>", {
action: data.delete_url,
method: "post"
}).appendTo($("td:last", row));
$("<div>", {
class: "btn-group"
}).appendTo($("form", row));
$("<a>", {
href: data.edit_url,
class: "btn btn-info btn-sm"
}).html("ویرایش").appendTo($(".btn-group", row));
$("<button>", {
type: "submit",
class: "btn btn-danger btn-sm job-destroy"
}).html("حذف").appendTo($(".btn-group", row));
return row;
}
$('#showJobs').append(addRow(myData));
If you add some small functions, you can easily use them to ensure that null does not appear in your HTML.
I have a page in asp.net core razor, which is updating the database. I use ajax to go to the controller, the world is done, but I am not able to update the list that the ajax method returns.
This is my ajax method:
$.ajax(
{
url: "/Uploader/Update",
type: 'post',
data: {
Id: valor
},
success: function (data) {
$("#LaudosDocumentos").html(data);
}
})
Here is my Controller:
public async Task<IActionResult> Update(int Id)
{
ApplicationUser user = await _userManager.GetUserAsync(User);
if (!ModelState.IsValid)
{
return NotFound();
}
Laudos = _context.Laudos.Find(Id);
Laudos.Excluido = true;
Laudos.AlteracaoUsuId = user.Id;
_context.Attach(Laudos).State = EntityState.Modified;
await _context.SaveChangesAsync();
Id = Laudos.PessoaId;
LaudosDocumentos = await _context.Laudos.Where(m => m.PessoaId == Id && m.Excluido == false).ToListAsync();
return Json( new { LaudosDocumentos });
}
This is my page cshtml:
<div class="col-sm">
#if (Model.LaudosDocumentos.Count > 0)
{
<label class="control-label" style="margin-left:10px">
Arquivo(s) encontrado(s)
</label>
}
else
{
<label class="control-label" style="margin-left:10px">
Nenhum arquivo foi enviado para analise.
</label>
}
<div class="btn btn-default btn-file">
#foreach (var item in Model.LaudosDocumentos)
{
var ponto = item.Caminho.IndexOf(".");
var extensao = item.Caminho.Substring(ponto + 1);
if (extensao == "png" || extensao == "jpg" || extensao == "gif" || extensao == "jpeg")
{
<a class="example-image-link" href="/uploads/#Html.DisplayFor(modelItem => item.PessoaId)/#Html.DisplayFor(modelItem => item.Caminho)" data-lightbox="example-set" data-title="">
<img src="/uploads/#Html.DisplayFor(modelItem => item.PessoaId)/#Html.DisplayFor(modelItem => item.Caminho)" class="img-thumbnail" alt="Laudos" style="width:200px; height:200px;" />
</a>
<span style="font-size:23px; margin-left:10px;"> <i class="far fa-trash-alt" onclick="ExcluirArquivo(#Html.DisplayFor(modelItem => item.Id));"></i></span>
<span> <i class="far fa-trash-alt" onclick="ExcluirArquivo(#Html.DisplayFor(modelItem => item.Id));"></i></span>
}
}
</div>
</div>
I just need to update the list Model.LaudosDocumentos
but without having to pass the Id of a div.
I've tried to pass the item value in ajax but it also didn't work.
Json( new { LaudosDocumentos }) will return Json data , you should create your html markup and associated with Json value using Javascript , here is code sample .
If you don't want to create html in javscript manually , you can put the whole <div> to partial view , and use ajax to call server side function to query/load the partial view with passed model/value , and at last in success function of Ajax directly load the html using .html(result); . Here is coed sample .
I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405
I wanted to change an input value based on the selection from a combobox in codeigniter. I tried to code it but theres nothing to be displayed.
Here is my code in my controller.....
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
$data .= $baseamount;
echo $data;
}
else
{
echo $data;
}
}
And in my Base_amount_setting_model there is this method....
function getbaseamount($group_id)
{
$this->db->where('group_id',$group_id);
$baseamount = $this->db->get('base_amount_setting')->row()->amount;
if($baseamount -> num_rows() == 1)
{
return $baseamount->result();
}
}
And there in my view the ajax looks like this.....
<script>
$(document).ready(function()
{
$("#group_id").change(function()
{
var group_id = $("#group_id").val();
$.ajax({
type : "POST",
url : "<?php echo base_url('payment/fill_info'); ?>",
data : "group_id=" + group_id,
success: function(data)
{
$("#base_amount").html(data);
}
});
});
});
</script>
and finally my form is like this...
<div class="control-group">
<label class="control-label" for="select01">Group Id </label>
<div class="controls">
<select class="chzn-select" name="group_id" id="group_id" placeholder="Group Id" value="<?php echo $group_id; ?>">
<option></option>
<?php
if (count($groups)) {
foreach ($groups as $list) {
echo "<option value='". $list['group_id'] . "'>" . $list['group_name'] . "</option>";
}
}
?>
</select>
<label for="int" class="err"><?php echo form_error('group_id') ?></label>
</div>
<input class="input-xlarge disabled" id="base_amount" name="base_amount" type="text" placeholder="Base Amount" disabled="">
<input class="input-xlarge disabled" id="total_members" type="text" placeholder="Total Members" disabled="">
</div>
Thank You!
change this $("#base_amount").html(data);
to $("#base_amount").val(data);
Actually if you get your value after ajax hit in data object
then only change this :
$("#base_amount").html(data);
to
$("#base_amount").val(data);
Actually .html replce the html not change the value.
i'm really curious - but i think your model doesnt return anything
try the following
function getbaseamount($group_id)
{
$query = $this->db
->where('group_id',$group_id)
->get('base_amount_setting');
if ($query->num_rows() == 1)
{
$obj = $query->row();
return $obj->amount;
}
}
and as others suggested
change your script code to
$("#base_amount").val(data);
and your controller function should look like
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
echo $baseamount;
}
else
{
echo $data;
}
}
I can't figure out why JSON isn't working in my comment system. Any help would be much appreciated.
Currently when I submit the comment form, the ajax-loader flashes and spins, but the comment doesn't load and I get the "unexpected token" syntax error. When I refresh the page however the comment appears.
Here is my AJAX event handler that goes directly to my controller (following code snippet):
($('document').ready(function(){
$("button.submit").bind('click', function (e){
e.preventDefault();
var form = $('form');
var submit = $('button#submit');
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="/img/ajax-loader.gif" />');
$.ajax({
type: 'POST',
cache: false,
url: '?comment='+comment+'&item='+item+'&author='+author+'&rating='+rating,
data: form.serialize(),
dataTYPE: 'json',
success: function( data ){
comment_insert( jQuery.parseJSON( data ) );
console.log( "ResponseText: " +data );
form.trigger('reset');
$("#flash").hide();
}
});
});
});
function comment_insert( data )
{
var insert = '';
insert += '<article>';
insert += '<p>';
insert += ''+data.comment+'';
insert += '—';
insert += ''+data.author+'';
insert += ' | Reply';
insert += '</p>';
insert += '</article>';
$('.comment_block').prepend( insert );
}
Controller:
if($this->request->is('post')) {
$comments = ItemComments::create($this->request->data);
$comments->author_id = $this->user->id;
$comments->comment = $this->request->data['comment'];
$comments->item_id = $this->request->data['item'];
$comments->author_id = $this->request->data['author'];
$comments->rating = $this->request->data['rating'];
$comments->save();
echo json_encode($comments);
}
view page:
<div class="col-lg-12">
<h4>Comments and questions:</h4>
<?php if (count($comments)): foreach ($comments as $feedback): ?>
<article>
<p>
<?=$feedback->comment?>
—
<a href="/users/<?=$feedback->author->url?>">
<?=$feedback->author->firstname?>
<?=$feedback->author->lastname?>
<?=$feedback->id?>
</a>|
Reply
</p>
</article>
<?php endforeach;?>
<?php else: ?>
<div class="col-lg-12">
<div class="well-sm text-center">
<i class="fa fa-comments fa-2x"></i>
<h4>No comments yet.</h4>
</div>
</div>
<?php endif; ?>
<div class="comment_block"></div>
<div id="flash"></div>
</div>