jQuery sortable serialize not recognizing dynamically added content - javascript

I am trying to re-order a list via ajax on sortable update, however after adding a new item to this list via ajax after sortable has already been initialized on page load, it does not recognize the new item with the "serialize" function. It does allow me to drag it around as though it is working, but the code that gets sent with my update function is missing the new element.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
$.post('admin/ereg_forms/set_category_position', serialized, function(data) {
if (data.status == 'error') {
alert(data.message);
}
});
}
});
//Add category submit
$("#add-category-submit").click(function(e) {
e.preventDefault();
$(".errors-block").html('');
$('#add-category-submit').hide();
$.ajax({
url: $("#add-category-form").attr('action'),
type: 'POST',
data: $('#add-category-form').serialize(),
dataType: 'json',
success: function(data) {
$('#add-category-submit').show();
//Check if server side validation passed
if (data.status == 'error') {
//Show error on popup dialog
$("#add-category-form .errors-block").html(data.message);
alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
} else {
var category_data = data.data;
var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>'
$(tableRow).appendTo('#categories-list tbody');
resetForm($('#add-category-form'));
//Close popup window
$('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}
},
error: function(data) {
alert('An unknown error has occurred, please try again.');
$('#add-category-submit').show();
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
I have looked everywhere for a solution but have not found one that has worked. I have tried using the "refresh" function with sortable, I have tried initializing sortable inside of the success function of the ajax call to add new categories but it also does not work.
when I console.log(serialized) it only has the originally loaded elements in the array.

IDK what is going on, but this fake add works, perhaps you can emulate this? Note I cleaned up a couple syntax issues and used the ajax promise methods to better organize it.
I suggest you update your jQuery version, some better stuff in more recent versions with bug fixes.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
// $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
// if (data.status == 'error') {
// alert(data.message);
// }
// });
}
});
$('#addmorefool').on('click', AddMore);
function AddMore() {
let tbody = $('#categories-list').find('tbody');
let rowscount = tbody.find('tr').length;
let newRow = '<tr id="category-row-' + rowscount + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td><td class="category-row-title">test' + rowscount + '</td></tr>';
tbody.append(newRow);
}
AddMore();
//Add category submit
$("#add-category-sumbit").on('click', function(e) {
//console.log("howdy");
e.preventDefault();
var myform = $("#add-category-form");
var errorBlock = myform.find(".errors-block");
errorBlock.html('');
errorBlock.dialog({
modal: true,
width: 'auto',
autoOpen: false
});
var catSub = $('#add-category-submit');
catSub.hide();
var myjax = $.ajax({
url: myform.attr('action'),
type: 'POST',
data: myform.serialize(),
dataType: 'json'
})
.done(function(data) {
catSub.show();
//Check if server side validation passed
var category_data = data.data;
var tableRow = $('<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>');
let tbody = $('#categories-list').find('tbody');
tbody.append(tableRow);
resetForm(myform);
//Close popup window (out cause have none)
//('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}).fail(function(data) {
//Show error on popup dialog
errorBlock.html('<span>Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.</span>' + data.message);
errorBlock.dialog("open");
//catSub.show(); (out cause not in code)
});
});
tr td {
border: 1px solid lime;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id="add-category-form" action="metoo">I am an empty form, so what
<div class="errors-block">me error aggain? no way</div>
</div>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
<button id="addmorefool" type="button">Add More</button>
<div class="errors-block">me error</div>
<button type="button" id="add-category-sumbit">add category</button>

I ended up solving this problem, the issue was in the add category function I was applying the "class" attribute instead of using the "id" attribute for the category-row-{id}.

Related

Ajax not sending data as parameters

I'm trying to send an array via ajax so I have the following code:
Here is the code
function fncGetChecksToProcess() {
var allChecks = [];
$('input[type=text]').each(function() {
var key = $(this).attr("id").replace("txt_", "");
allChecks[key] = [];
});
$('input[type=checkbox]').each(function() {
if (this.checked) {
var className = $(this).attr('class');
if (className.includes('box_total_')) {
var ref = $(this).attr('id').replace("box_total_", "");
var amountDetails = [];
var docNs = [];
$('.' + ref).each(function() {
amountDetails.push(parseFloat($(this).closest('td').next().html().replace("$", "").replace(",", "")));
docNs.push($(this).attr('id').replace("box_", ""));
});
allChecks[ref].push({
docN: docNs,
amountTot: $("#sub_" + ref).text(),
amountDetails: amountDetails,
chkNum: $("#txt_" + ref).val()
});
} else {
var docN = $(this).attr('id').replace("box_", "");
allChecks[className].push({
docN: docN,
amountTot: $("#td_" + docN).text(),
amountDetails: "",
chkNum: $("#txt_" + className).val()
});
}
}
});
return allChecks;
}
$(document).ready(function() {
$("#btn").click(function() {
var checks = fncGetChecksToProcess();
console.log(checks);
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks
},
url: '/process',
beforeSend: function() {
console.log("Processing your checks please wait...");
},
success: function(response) {
console.log(response);
},
error: function() {
console.log("Error");
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js"></script>
</head>
<body>
<table id="table" class="tablesorter" width="100%" cellspacing="0">
<thead>
<tr>
<th>H1</th>
<th>H2</th>
<th>H3</th>
<th>H4</th>
<th>H5</th>
<th></th>
<th>H6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>11002WR</td>
<td>201100</td>
<td>A</td>
<td class="center"><input class="11002WR" id="box_201100" type="checkbox" /></td>
<td id="td_201100">$320.00</td>
</tr>
<tr>
<td colspan="3"></td>
<td>Check. No</td>
<td><input id="txt_11002WR" type="text"></td>
<td><input id="box_total_11002WR" class="box_total_201100" type="checkbox" /></td>
<td id="sub_11002WR">$12.00</td>
</tbody>
</table>
<input id="btn" type="button" value="Test" />
</body>
</html>
Please check the two checkboxes and the input and press on the test.
The console prints out the array generated but Ajax does not send it.
Why my ajax call does not send any parameters? I don't see them in chrome console.
Thanks.
Since your keys are strings, not numbers, you should be using an object, not an array. Change
var allChecks = [];
to
var allChecks = {};
When you send an array with $.ajax, it only sends the elements with numeric indexes, not named properties.
You need to send an array to ajax , now you send an array of array inside array...
if you post to the server like form the post will looks like:
allchecks[] = x
allchecks[] = y ...
https://plnkr.co/edit/SnZmKgRLODYb8p6kPryn?p=preview
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks["11002WR"][0]
},
this is a fast solution for you . but it is not a good practice
instead of allchecks=[] . try to build objects with keys or ids and not string like the ref as a key of the array
objects is like the following :
var allChecks = {};

Redrawing data table causes data lost

I've a test case where I need to reload table rows when the user changes input fields and clicks submit button. When the table is first initialized, table body is empty. And then I make a ReST call to get the JSON data and construct the tbody html. Problem I'm facing is that one of the column in the table is supposed to be visible. But since the html markup is being created after the table is initiated, the column that is supposed to be hidden is showing up. I tried to call the draw() function on the table API but that is causing the data to be lost. Is there any other way I can do this?
HTML
<p>
<input type="text" name="startDate" id="startDate"/><br/>
<input type="text" name="endDate" id="endDate"/><br/>
<button type="button" id="refresh">Refresh</button>
</p>
<table id="myTable" style="width: 400px;">
<thead>
<tr>
<th class="no-show">Col A</th>
<th>Col B</th>
<th>Col C</th>
<th>Col D</th>
<th>Col E</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Script
<script type="text/javascript">
var table;
$(document).ready(function(){
var table = $("#myTable").dataTable({
"paging": true,
"pageLength": 5,
"pagingType": "simple",
"info": false,
"order": [[2, "desc"]],
"aoColumnDefs":[
{"aTargets": ["no-show"], "bVisible": false}
],
"fnInitComplete": function(oSettings, json){
$(".dataTables_filter, .dataTables_length").hide();
}
});
refreshTable(table);
$("#refresh").on('click', function(){
refreshTable(table)
});
});
function refreshTable(table)
{
var data = "startDate="+$("#startDate").val()+"&endDate="+$("#endDate").val();
var url = "data.json";
$.ajax({
url: url,
type: "GET",
async: false,
data: data,
success: function(data){
var tbodyHtml = "";
for(var i=0; i< data.length ; i++)
{
tbodyHtml += "<tr>";
tbodyHtml += "<td class='no-show'>"+data[i].eid+"</td>";
tbodyHtml += "<td>"+data[i].firstName+"</td>";
tbodyHtml += "<td>"+data[i].lastName+"</td>";
tbodyHtml += "<td>"+data[i].department+"</td>";
tbodyHtml += "<td>"+data[i].manager+"</td>";
tbodyHtml += "</tr>";
}
$("#myTable tbody").html(tbodyHtml);
table.api().draw();
}
});
}
</script>
P.S. the tbody html I've here is pretty basic. I actually have to do a bit of logic on the data before populating the table. That's why I didn't use Datatable's in built AJAX api.

After prepend, set value as input javascript then process values in php script

I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "Pošalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});

After a successful AJAX call cant update td data

Thanks For viewing this post.i am facing a jquery issue .After a successful AJAX call, I want to update an element on page. However, it is not being updated.
what am i doing i am opening a text box on click of span then add text and and on focus out event i am making Ajax call but cant update new text to same span when that i clicked before please help me
here is my js code
$(document).on('click', '.td-edit', (function (e0) {
var thisObj = $(this);
var olddata = thisObj.html();
var newDom = '<input type="text" value="' + olddata + '" class="new-value" style="border:#bbb 1px solid;padding-left:5px;width:75%;"/ >';
thisObj.parent('td').html(newDom);
}));
$(document).on('focusout', '.new-value', (function (e1) {
var thisObj = $(this);
var type = thisObj.parent('td').attr('class');
var newData = thisObj.val();
var santanceId = thisObj.parent('td').parent('tr').attr('id');
santanceId = parseInt(santanceId.replace('tr', ''));
thisObj.parent('td').html('\'<img src="uploads/loading.gif">\'');
if (type === 'sentnc') {
$.ajax({
type: "POST",
url: "operations.php",
data: {
santanceId: santanceId,
sentnc: newData
},
success: function () {
var newDom = '<span class="td-edit">' + newData + '</span>';
thisObj.parent('td').html(newDom);
}
});
}
}));
HTML:
<div class="chat-space nano nscroller">
<div id="table-row">
<table id="rep-data">
<tbody>
<tr>
<th align="left">Sentences</th>
<th align="left" colspan="3">Reps</th>
</tr>
<tr id="tr1" rowspan="2">
<td class="sentnc"><span class="td-edit">Rana is working</span></td>
<td colspan="3" class="senrep"><span class="td-edit">p1.ref = I, p1.name = julie</span><br>
<br>
<span style="color:#000;">Guess Rep1: </span><span id="1gr1">p1.ref = I, p1.has = name1, p1.name.made_from = rana</span><br>
<span style="color:#000;">Guess Rep2: </span><span id="2gr1">p1.ref = I, p1.name = rana</span><br>
<span><a style="color:#3399FF !important;" alt="1" rel="1 " class="updateGuess" id="upd1" href="javascript:void(0);">Update Guess Rep</a></span><br>
<br></td>
</tr>
</tbody>
</table>
</div>
Your success handler should be:
success: function (data) {
var newDom = '<span class="td-edit">' + data + '</span>';
thisObj.parent('td').html(newDom);
}
Here, the data is the data returned by your server, after the ajax Call

How to get the value of the first td of the table using JQuery?

I have a table where in I have binded the values which are coming from the Form.In that form I have a primary key Field as TicketId which I have kept as hidden in the form and while inserting it into the table I am showing it.For Binding the data I have used Knockout.So I want to delete the row that I will select.So while selecting it I should get the id of that row so that I can passed it to the Delete action using ajax.But My problem is that I am not getting that id.So how to do this?
My code:
<table id="table2" style="border: double">
<thead>
<tr>
<td>Ticket ID</td>
<td>Ticket Type</td>
<td>No of Tickets</td>
<td>Ticket Price</td>
<td>Start Date</td>
<td>End Date</td>
<td>Action</td>
</tr>
</thead>
<!--Iterate through an observableArray using foreach-->
<tbody id="ticketid" data-bind="foreach:TicketDatas">
<tr style="border: solid" data-bind="click: $root.getselectedTicket" id="updtr">
<td id="rowid" data-bind="text:TicketId">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:SelectedTicketType">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:No_Of_Ticket">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:Ticket_Price">#*<span data-bind="text:Ticket_Price"></span>*#</td>
<td data-bind="text:Start_Date">#*<span data-bind="text:Start_Date"></span>*#</td>
<td data-bind="text:End_Date">#*<span data-bind="text:End_Date"></span>*#</td>
<td>
<button data-bind="click: $root.deleterec">Delete</button></td>
</tr>
</tbody>
</table>
<script type="text/javasript">
self.deleterec = function () {
if (confirm('Are you sure to Delete this ticket ??')) {
var tickid = $("#table2 tr:eq(0)").attr("id");
$.ajax({
type: "POST",
data: { id: tickid },
url: "Ticket/DeleteTicket",
//data: "{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.TicketDatas.remove(data);
alert("Record Deleted Successfully");
//GetTickets();//Refresh the Table
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
}
};
</script>
so just want the solution for this statement if I ask in short
var tickid = $("#table2 tr:eq(0)").attr("id");
I'm not sure how the rest of your code goes, but here's the jQuery parts when you have a reference to the DOM node for the delete link.
I assigned most parts to variable names to be more descriptive here, but you can make this more concise for your use.
$('#table2 .delete-link').click(function() {
var deleteLink = $(this);
var tableRow = deleteLink.closest('tr');
var firstCell = tableRow.find('td:first-child');
var ticketId = firstCell.attr('id');
// ... Do what you need to do with the ticket ID.
return false;
});
Additional References:
CSS pseudo-class :first-child
jQuery click()
jQuery closest()
jQuery find()
var tickid = $("#table2 tr:eq(0)").html();
OR
var tickid = $("#table2 tr:eq(0)").val();

Categories

Resources