Sort ajax data in table with tablesorter.js - javascript

I'm trying to use tablesorter.js but im running into issues when using ajax to update my table. I followed the code on this page but it doesn't seem to be working properly. One thing i also notice is that the code doesnt work properly even on the example website. When i click "append new table data" it adds the data to the table but it isn't sorting it correctly. If i copy the javascript code and paste it into the console, it works fine and sorts the table correctly. The code im using is the following:
var updateTableSort = function(){
var table = $('#transaction-table')
//tells table sorter that table has been updated
table.trigger("update");
//re sorts after table has been updated based on
//current sort patern
var sorting=table.get(0).config.sortList;
table.trigger('sorton', [sorting]);
}
Again, if i copy and past this into console it works fine, but when i have it in my success ajax function, it doesnt sort the table properly. Any help figuring out what the issue is would be greatly appreciated

Try my fork of tablesorter. It automatically resorts the table after an update:
// pass anything BUT false and the table will resort
// using the current sort
$("table").trigger("update", [false]);
Here is the updated append data to the table using ajax demo:
$(function() {
$("table").tablesorter({ theme : 'blue' });
$("#ajax-append").click(function() {
$.get("assets/ajax-content.html", function(html) {
// append the "ajax'd" data to the table body
$("table tbody").append(html);
// let the plugin know that we made a update
// the resort flag set to anything BUT false (no quotes) will
// trigger an automatic
// table resort using the current sort
var resort = true;
$("table").trigger("update", [resort]);
// triggering the "update" function will resort the table using the
// current sort; since version 2.0.14
// use the following code to change the sort; set sorting column and
// direction, this will sort on the first and third column
// var sorting = [[2,1],[0,0]];
// $("table").trigger("sorton", [sorting]);
});
return false;
});
});

Related

JQuery - Why this variable doesn't lose its value after the function was executed?

I'm new to JQuery and I'm trying to define a JQuery function with the purpose of edit a table row: a modal asks for the new values and then, the function update the table row content. But when I select the row I want to edit, the variable in which the row was stored "accumulates" all the previous rows that have been edited in the same object and when I try to update the new values to this single row, all the rows edited before receive and show the same value. Why is this happening?
I'll show you the code:
$("#table").on("click", ".edit", function() {
var table = $("#table").DataTable();
var row = $(this).closest("tr");
//getting the <tr> content with Datatables API:
var values = $table.row(row).data();
$("#name").val(values[0]);
$("#surname").val(values[1]);
$("#city").val(values[2]);
$("#myModal .modal-footer").on("click", "#confirm", function() {
var newValues = []
//getting the <tr> content with Datatables API:
//this alert appears as many time as many rows have been changed
alert($table.row(row).data());
//deleting the old data from the server...
//getting the new values:
newValues.push($("#name").val());
newValues.push($("#surname").val());
newValues.push($("#city").val());
//adding the new date to the server...
$("#myModal").modal("hide");
//update the html table:
table.row(row).data([newValues[0], newValues[1], newValues[2]]);
});
});
As I've explained before, the variable "row" in the .on("click")
function "accumulates" all the rows that have been edited before.
I thought it was a scope probelm, so I've also tried to call an extern function which basically did the same things and took advantage of the event.data object:
$("#confirm").on("click", {table: table, row: row}, edit);
but with no luck. If any one can help me or even provide me some advice or documentation, it would be very appreciated.
You have to use two different and independent functions using an external variable to connect them; you can't use .on() in a nested way

datatables Cannot reinitialise DataTable and destroy is not working

I have tried all the commands for destroy and empty of the datatable after selecting a new option, and is not working.
this is some part of my js file that contains the ajax. it uses dynamic urls apis.
function table(url, columns) {
var dt = $("#datatables").dataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": url,
"type": "GET",
},
"columns": columns,
lengthMenu: [[25, 100, 250, 500], [25, 100, 250, 500]],
pageLength: 25,
// destroy: true
});
... // more stuff here about the design of the table
}
$("form#btnGetDomain").on("submit", function (ev) {
ev.preventDefault();
ev.stopPropagation();
// $("#datatables").dataTable().fnDestroy();
var url;
var columns;
var categ = document.getElementById("categ").value;
// this is where i do if statements depending what options was selected
// i get the proper url api
...
table(url, columns);
});
i have tried all those commands:
$("#datatables").dataTable().fnDestroy();
$("#datatables").empty();
destroy: true,
The command "destroy: true" inside the dataTable i don't know if it works properly because after i try to select the second time another option, the table doesn't responde, it just says ** Processing....**
I also tried to put the comand inside the on submit function before i select any option to clear the table. Now i m thinking of doing an if statement, if their is a table, clear it.
Thank you
UPDATE
i ve tried with dataTable and DataTable
**UPDATE 2 **
if ($.fn.DataTable.isDataTable("#datatables")) {
$("#datatables").DataTable().clear().draw();
$("#datatables").dataTable().fnDestroy();
}
This command i have put before the var dt = $("#datatables").dataTable({...
Yes i noticed i used small and big cap datatable...but this worked ...i did try to put both with big D but didn't work... also tryed to use in the last one: DataTable().destroy();...didn't work
Example: using videos and channels
I have selected the first time videos.
After i select channels:
It changes the columns names no problem ( i have different columns names for every api)... but the rows remain the same.
When i select back to videos.
Column names change, and rows are changing to previous selection which was channels.
Hope you can understand. It doesn't really make sense why i have to use dataTable and DataTable...
it does change, but wrong changes...at least i am getting closer to the answer, hopefully.
I found out the answer i put this lines of code at the beginning of the table function
function table(url, columns) {
var dt;
if ($.fn.DataTable.isDataTable("#datatables")) {
$("#datatables").DataTable().clear().draw();
$("#datatables").DataTable().destroy();
$("#datatables thead").html('');
}
...
}
It works for me fine, it clears the rows, destroys the table, and empty the thead.
Oh..and i have change from lower case dataTable too upper case DataTable
Update: Did you try clear command? https://datatables.net/reference/api/clear()
$('#datatables').DataTable().clear().draw();
Another thing you could try is using the variable to destroy the table:
var dt = $('#datatables').DataTable({...init stuff...});
dt.destroy();
This could be a dt version issue. Did you try:
$('#datatables').DataTable().destroy();
Please notice the difference dataTable vs DataTable.

Kendo UI Grid Excel Export exporting twice

I wrote up some javascript code to export an excel grid that would only export the records filtered on the page by the filter tab and not the total value of records brought back. So for example if the record pulls back 23 records but you only have the view set to 10 you'll only get 10 records exported. I'm loading this function on the grid initialization as I usually do, however, for some reason it always seems to print out an empty sheet first with just the header rows, followed by the actual sheet I need. So the code is working but I can't figure out how to stop the first empty sheet from downloading as well. I don't believe I'm calling the method twice and there's definitely no looping logic... I've read over the Telerik documentation and I figured I'd come to stackoverflow since the Telerik support team just seems to refer everyone back to the same documentation
excelExport: function (e) {
var items = grid.dataSource.pageSize();
sheet = e.workbook.sheets[0];
var newSheet = sheet.rows.splice(0, items + 1) // +1 is for the header row
sheet.rows = newSheet
},

Use Datable with Nodejs socket.io

I'm currently starting using Datatables (https://datatables.net) to create tables.
The data in the table are obtained through socket.io from the server.
My problem is when socket.io add data, the table isn't "updated", it says it only have 1 entry and search box is only working on the last element added.
Here is a sample of my code:
socket.on('jobStepsResponse', function(message) {
document.getElementById('listOfJobs').style.display = 'none';
document.getElementById('contentJob').style.display = 'block';
document.getElementById('jobid').innerHTML = "<button onClick=returnToJobList()>Retour</button> Job "+message.idJob;
for(var i=0;i<Object.keys(message.status).length;i++){
document.getElementById('tabstats').innerHTML += '<tr><td>'+Object.keys(message.status)[i]+'</td>'+'<td>'+ts2time(message.status[Object.keys(message.status)[i]])+'</td>'+'</tr>';
}
$(document).ready(function() {$('#example2').DataTable();} );
setInterval( function () { $('#example2').DataTable().ajax.reload( null, false ); }, 1000 );
});
As you can see, I tried using ajax reload but i think its for ajax data sources, so it doesn't work.
As a workaround, i wait for table to be fully populated first, the call the Datatables style which will count all the element added.
Only problem is that it show the unformatted datas for some times so you need to add a DOM control to show a loading thing for example.

jquery footable $('#classes').trigger('footable_redraw'); return hidden table

this is my first Question, may be hard to understand.
calling $('#classes').trigger('footable_redraw'); , it return the data but hide the table heading and data rows,but when i used $('#classes').trigger('footable_initialize'); its work fine but reduplicate the data .
Ajax method is called on submitting form.
$.ajax({
url : baseurl+'index.php/settings/classes/viewclasses',
success : function(data) {
$('.classestbody').append(data);
$('#classes').trigger('footable_redraw'); }
});
How can i only get my updated data in table after saving any Values by calling submitting for saving ?
Basically you need to check to see if the data is in the table already. If the data is not in the table, add it; if it is in the table, don't. You'll need some way to positively identify a row that matches the data. If data is an array, you'll need to loop through the array and check each row.
Another option would be to use a data binding framework. This would allow you to bind the data to the table, then you just add/update/delete rows from the data and the framework takes care of updating the table (view) for you.
I personally use Knockout.js. They have a really good tutorial: http://learn.knockoutjs.com/. Even if you don't end up using Knockout.js, I think the tutorial is pretty cool and it will only take you a couple of hours to go through all of them.
If your script on index.php/settings/classes/viewclasses always returns the hole table, and since you said the data gets duplicated this seems to be the case.
Then it is easier to delete all rows then add them all again, just add $('.classestbody').empty(); before $('.classestbody').append(data);. Your code would look like this:
$.ajax({
url : baseurl+'index.php/settings/classes/viewclasses',
success : function(data) {
$('.classestbody').empty();
$('.classestbody').append(data);
$('#classes').trigger('footable_redraw');
}
});

Categories