I have table where I loop dynamic data and each of those dynamic items has input fields then I send those input fields along with dynamic items id to back-end.
Issue
Issue is that my fields in ajax giving me strange data as array.
Code
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.newservicesSave').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var idmess = $(this).data("id");
// this array data are wrong
var newservices = [];
$(".newservices").each(function() {
newservices.push($(this).val());
});
console.log('newservices: ', newservices);
$.ajax({
url: '{{ url('
panel / addnewservices ') }}/' + encodeURI(idmess),
type: 'POST',
dataType: "JSON",
data: {
"id": idmess,
"newservices": newservices,
"_method": 'POST',
"_token": "{{ csrf_token() }}",
},
success: function(data) {
$('#servicesTable').empty();
$.each(data.data, function(key, value) {
$("#servicesTable").append('<tr><td>' + value['name'] + '</td><td><textarea name="' + services['key']['description'] + '" class="form-control" name="description"></textarea><input type="hidden" name="' + services['key']['service_id'] + '"/></td><td><input type="text" class="form-control" placeholder="Harga" name="' + services['key']['price'] + '"/></td><td><input class="form-checkbox" type="checkbox" name="' + services['key']['active'] + '" /></td></tr>');
});
}
});
});
});
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Service</th>
<th>Description</th>
<th>Harga</th>
<th>Active</th>
</tr>
</thead>
<tbody>
#foreach($services as $index => $service)
<tr>
<td>{{$service->name}}</td>
<td>
<textarea name="newservices[{{$index}}][description]" class="newservices form-control" name="description"></textarea>
<input type="hidden" class="newservices" name="newservices[{{$index}}][service_id]" />
</td>
<td>
<input type="text" class="newservices form-control" placeholder="Harga" name="newservices[{{$index}}][price]" />
</td>
<td><input class="newservices form-checkbox" type="checkbox" name="newservices[{{$index}}][active]" /></td>
</tr>
#endforeach
</tbody>
</table>
<button type="button" data-id="{{$laundry->id}}" class="newservicesSave btn btn-primary">Save changes</button>
Result
Expected data from ajax
Data should come to backend as follow structure
newservices [
0 [
active => 0,
service_id => '123456',
description => 'abc',
price => '1000'
],
1 [...],
2 [...],
// etc.
]
Any idea?
To get the structure you want you will need to loop over rows and create an object for each row
Try something like :
var newservices = $('#myTable tbody tr').map(function(){
var $row = $(this);
return {
description: $row.find('.newservices[name*="description"]').val(),
service_id : $row.find('.newservices[name*="service_id"]').val(),
// ... same for other properties
}
}).get();
Related
I have a function where i can add rows and autonumbering. The add rows works when you click the "add row" button, and auto numbering works when you press Ctrl+Enter key when there's 2 or more rows. My problem is, my validation does not work on my autonumbering.
For example: when I type manually the "1" on the textbox, it works.
But when I do my auto numbering, "Not good" does not appear on my 2nd
textbox.
Is there anything I missed? Any help will be appreciated.
//this is for adding rows
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
const inputs = document.querySelectorAll(".form");
document.querySelectorAll(".form")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You can call your event handler i.e : change whenever you change your input values by auto numbering . So , use $(this).trigger("change") where this refer to input where value is changed .
Demo Code :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
$(document).on('keyup', '.form', function(e) {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
//loop through all values...
$(".form").each(function(i) {
if (i !== 0) {
$(this).val(++value); //assign new value..
$(this).trigger("change") //call your change event to handle further...
}
})
}
})
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
I am getting some data using ajax but I cannot pass diffForHuman() function to get different format of date. I want date in another format. But by passing created_at to my markup then it is giving me undefined date. Below is my code. Pls help
//Javascript
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$('select[name="class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/attendance/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
markup += '<tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 2%" class="align-middle text-center">#</th> <th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Attendance<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Date<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr>';
$.each(data, function(key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]"></td> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td><input type="hidden" value="'+value.student_id+'" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="'+value.first_name+'" name="first_name[]"><input type="hidden" value="'+value.last_name+'" name="last_name[]">' + value.first_name+ ' ' + value.last_name + '<td><input type="hidden" value="'+value.attendance+'" name="attendance[]">' + value.attendance + '</td>' + '<td><input type="hidden" value="'+value.created_at+'" name="created_at[]">' + value.created_at + '</td>' + '<td style=" width=12%" class="text-center"> <a><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function student_attendance_registers() {
$attendances = StudentsAttendance::all();
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.student_attendance_registers', compact('attendances', 'classes'));
}
//Model
class StudentsAttendance extends Model
{
protected $fillable = [
'class_id',
'student_id',
'first_name',
'last_name',
'attendance'
];
public function studentsClass() {
return $this->belongsTo('App\StudentsClass');
}
public function getdateForHumansAttribute()
{
return $this->created_at->diffForHumans();
}
public function toArray()
{
$data = parent::toArray();
$data['diffForHumans'] = $this->diffForHumans;
return $data;
}
}
The best way to do this, would be to add a getdateForHumanAttribute method:
public function getdateForHumansAttribute()
{
return $this->created_at->diffForHumans();
}
Then on your model you can use anywhere:
$model->dateForHumans;
For an easy way to always add dateForHumans attribute when you retrieve this model, add it to toArray method:
(Also on your model)
public function toArray()
{
$data = parent::toArray();
$data['diffForHumans'] = $this->diffForHumans;
return $data;
}
We are trying to send multiple associative array values from javascript/ajax to php but we receive an empty object/array at the php file.
So can you please help to get values of an associative array from javascript to php?
We have tried serializing array and passing to a php file.
We have tried to convert an array to string and then try to pass it to a php file.
Please check the following code:
// javscript
function saveData(id) {
//var actionData = [];
var actionData = $('#' + id).closest('tr').find("[id^='action_']");
var ownerData = $('#' + id).closest('tr').find("[id^='owner_']");
//var type = $.type(actionData);
//alert(type); exit();
/*alert(actionData[0]['action']);exit;
actionData['owner'] = $('#' + id).closest('tr').find("[id^='owner_']");
actionData[2]['dueDate'] = $('#' + id).closest('tr').find("[id^='dueDate_']");
actionData[3]['completedDate'] = $('#' + id).closest('tr').find("[id^='completedDate_']");
//var myData = JSON.stringify(actionData['owner']);
//alert($('#' + id).closest('tr').find('#projId').val());*/
var dataObject = [];
dataObject['projId'] = $('#' + id).closest('tr').find('#projId').val();
//alert(myData);
//var newData1 = $.extend({}, actionData['owner']);
var newData = $.extend({}, dataObject);
/*dataObject = {
projId: $('#' + id).closest('tr').find('#projId').val(),
riskNumber: $('#' + id).closest('tr').children('td#riskNumber').text().slice(0,-4),
cause: $('#' + id).closest('tr').find('#cause').val(),
effect: $('#' + id).closest('tr').find('#effect').val(),
functionAffectedControl: $('#' + id).closest('tr').find('#functionAffectedControl :selected').val(),
categoryControl: $('#' + id).closest('tr').find('#categoryControl :selected').val(),
impact: $('#' + id).closest('tr').find('#impact :selected').val(),
severityControls: $('#' + id).closest('tr').find('#severityControls').val(),
probability: $('#' + id).closest('tr').find('#probability :selected').val(),
riskOwnerControl: $('#' + id).closest('tr').find('#riskOwnerControl :selected').val(),
manageability: $('#' + id).closest('tr').find('#manageability :selected').val(),
residualProbability: $('#' + id).closest('tr').find('#residualProbability :selected').val(),
residualImpact: $('#' + id).closest('tr').find('#residualImpact :selected').val(),
statusControl: $('#' + id).closest('tr').find('#statusControl :selected').val()
//actions: JSON.stringify(actionArray)
//owners: $('#' + id).closest('tr').find("[id^='owner_']").val(),
//dueDates: $('#' + id).closest('tr').find("[id^='dueDate_']"),
//CompletedDates: $('#' + id).closest('tr').find("[id^='completedDate_']")
}*/
$.ajax({
type: "POST",
url: "/apps/projmgmt/reports/SaveData.php",
data: { data: actionData, owner:ownerData}, //
dataType: 'json',
success: function(response) {
console.log(response);
alert('Data Saved Successfully');
}
});
}
// html
<table class="table table-bordered table-striped tree-basic">
<tbody>
{foreach from=$obj->getRiskActionList() name=risk item=risk}
<tr class="{$class}" data-count="2" id="{$k}">
{$i = $i+1}
{$class='treegrid-'|cat:$i}
{$j = $i-1}
{$classNode='treegrid-parent-'|cat:$j}
<td style="font-weight: bold;">
<div class="treegrid-container">
<span class="treegrid-expander treegrid-expander-collapsed"></span>
{'ACTION'|gettext|escape}</div>
</td>
<td colspan="6" >
<input type="hidden" name="actionId[]" id="actionId_{$k}" value="{$risk->getId()|escape}" />
<div class="treegrid-container">
<span class="treegrid-expander"></span>
<textarea rows="2" cols="100" id="action_{$k}" name="mitigationAction[]" maxlength="256">{$risk->getMitigationAction()|escape}</textarea></div>
</td>
</tr>
<tr class="{$class} {$classNode}">
{$i = $i+1}
{$class='treegrid-'|cat:$i}
<td style="font-weight: bold;" >
<div class="treegrid-container">
<span class="treegrid-expander"></span>{'OWNER_NAME'|gettext|escape}</div></td>
<td>
<input type="text" name="actionOwner[]" size="50" id="owner_{$k}" value="{$risk->getOwnerName()|escape}" maxlength="80"/>
</td>
<td style="font-weight: bold; text-align: center;" >{'DUE_DATE'|gettext|escape}</td>
<td>
<input type="hidden" class="riskPopupCalendar" id="actionDueDate_{$i}" name="actionDueDate[]" value="{$smarty.request.actionDueDate[$i]|escape}">
<div size="10" name="actionDueDateText[]" id="dueDate_{$k}">{if null != {$risk->getDueDate()|escape}}{$risk->getDueDate()->format('d/m/Y')|escape}{/if}</div>
<img src="/images/calendar.gif" id="actionDueDateDatepicker_{$i}" style="width:16px;height:16px;">
<a href="#"><img src="/images/calendar_delete.gif" class="riskPopupCalendarDelete" style="width:16px;height:16px;"
data-input="actionDueDate_{$i}" data-text="actionDueDateText_{$i}" id="actionDueDateDelete_{$i}"></a>
</td>
<td style="font-weight: bold; text-align: center;" >{'COMPLETED_DATE'|gettext|escape}</td>
<td>
<input type="hidden" class="riskPopupCalendar" id="actionCompletedDate_{$i}" name="actionCompletedDate[]" value="{$smarty.request.actionCompletedDate[$i]|escape}">
<div size="10" name="actionCompletedDateText[]" id="completedDate_{$k}>{if null != {$risk->getCompletedDate()|escape}}{$risk->getCompletedDate()->format('d/m/Y')|escape}{/if}</div>
<img src="/images/calendar.gif" id="actionCompletedDateDatepicker_{$i}" style="width:16px;height:16px;">
<a href="#"><img src="/images/calendar_delete.gif" class="riskPopupCalendarDelete" style="width:16px;height:16px;"
data-input="actionCompletedDate_{$i}" data-text="actionCompletedDateText_{$i}" id="actionCompletedDateDelete_{$i}"></a>
</td>
</tr>
<tr class="{$class} {$classNode}">
<div class="treegrid-container">
<span class="treegrid-expander"></span>
<td data-column="name"><img src="/images/blank.gif" class="ib_left"><input type="button" id="{$k|escape}" name="removeActionButton" value="{'REMOVE_ACTION'|gettext|escape}" class="removeActionButton ib"><img src="/images/blank.gif" class="ib_right"></td></div>
</tr>
{$i = $i+1}
{$k = $k+1}
{$class='treegrid-'|cat:$i}
{/foreach}
<tr>
<td></td><td></td><td></td><td></td><td></td>
<td align="right"><img src="/images/blank.gif" class="ib_left"><input type="button" onclick="updateData('{$row}','{$k}');" data-number="{$i}" value="{'ADD_ACTION'|gettext|escape}" class="addActionButton ib"><img src="/images/blank.gif" class="ib_right"></td>
</tr>
</tbody>
</table>
First ensure you data is what you think it is:
var data = JSON.stringify({ data: actionData, owner:ownerData})
console.log(data)
If it is then sent the data object in your ajax call. Then on the the php side I would confirm that the received data matches the sent data. Then parse said data. This should help you narrow down and resolve your issue(s).
I tried to send information via ajax about user_question and language input fields, but how to write correctly this element inside ajax javascript to save the table element value in database.
thank you.
the script element.
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '</td>
<td class="col-md-2">' . HTML::inputField('language', null, 'placeholder="Language"') . '</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// element pb
// var data = $("#new_product").serialize(); // form id or table id ?
var dataString = 'user_question='+user_question+'language='+language;
$.ajax({
type: 'POST',
url: '{$ajax_url}',
data : dataString,
success: function(data) {
alert(data);
$("p").text(data);
}
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
Use like this to get php variables value inside javascript in .php page
url: "<?php echo $ajax_url; ?>",
Also use & and symbol to add two or more param in your dataString
Html code:
Below image describes my output.Please kindly some one help me to resolve this issue.
<table class="table table-striped table-bordered table-hover table-condensed tableSiteUser">
<thead>
<tr>
<th>#</th>
<th>SiteName</th>
<th>UserName</th>
<th>Channel</th>
<th>Action</th>
</tr>
</thead>
<tbody id="site-table-body">
<tr>
<td class="countsiteuser">1</td>
<td><select class="form-control" id="siteContainer"></select>
</td>
<td><input type="checkbox" value="user" id="checkboxbutton"><input type="text" class="and" disabled placeholder="Default"/></td>
<td><input type="text" class="form-control" placeholder="Enter the Channel"/></td>
<td><span class="form-control glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>
JavaScript:
$('.tableSiteUser').on('keydown','td:nth-child(4)',function(e){
var keyCode=e.keyCode || e.which;
if(keyCode == 9){
serialUserSite++;
$('tbody#site-table-body').append('<tr>'
+'<td class="beer" contenteditable="false">'+serialUserSite+'</td>'
+'<td><select class="form-control" id="siteContainer">'
+'</select></td>'
+'<td><input type="checkbox" value="user" id="checkboxbutton"><input type="text" class="and" disabled placeholder="Default"/></td>'
+'<td><input type="text" class="form-control" placeholder="Enter the Channel"/></td>'
+'<td><span class="glyphicon glyphicon-trash form-control"></span></td>'
+'</tr>');
}
});
ajax code:
$.ajax({
url : "http://localhost:8080/IDNS_Rule_Configuration/idns/systemData/getAllSites",
type : "GET",
contactType : "application/json",
dataType : "json",
success : function(data){
for(var i=0;i<data.length;i++){
var dataId = data[i].siteId;
var dataArray = data[i].siteName;
$('#siteContainer').populate(dataId, dataArray);
}
}
});
populate jquery code:
$.fn.populate = function(dataId, dataArray) {
var $selectbox = $(this);
// check if eleme nt is of type select
if ($selectbox.is("select")) {
//for (var i = 0; i < dataId.length; i++) {
$selectbox.append('<option value="' + dataId
+ '" stream="' + dataId + '">'
+ dataArray + '</option>');
//}
}
};
This is my output ,site name combo box is loaded from db.In first row it works .At second row it does not work