Reputation: 2422
I'm having a datatable with filters. I use Ajax every 10 seconds to fetch new data and add new rows to the table. (table data are dynamic in the same page not by ajax)
$(function () {
setInterval(checkNew,1000*10);
$( "#orderdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: '2013:2050',
dateFormat:"dd-mm-yy",
showAnim:"fold"
});
var table = $('#data').DataTable({
"lengthMenu": [[-1], ["All"]],
"bSort": false,
"paging": false,
});
$("#status").change(function() { table.column(4).search($(this).val()).draw() });
});
function checkNew(){
$.post('getdata.php',{max: $("#lastid").text().trim() }).done(function (data) {
if( data.trim() !== '' ) {
$("table#data").prepend(data.trim());
//need to draw datatable to filter and search new data added to the table
}
});
}
As you see i'm trying to update or draw the table with new data so I can filter or search them. If i search for new data it won't be displayed because it wasn't loaded with the DOM. But I can't redraw the table I've tried
$("table#data").DataTable().draw(); // new rows are added but can't be searched or filtered
And
$('table#data').dataTable().fnDraw(); //new rows are not added
So how to edit the code in anyway to correctly draw the table to filter and search new added data?
Upvotes: 0
Views: 3061
Reputation: 1183
Datatables provides built-in functionality for handling loading data from an ajax request into a table. Additionally, it provides a reload method that will refresh the data in the table.
In your case, you should be able to do something like:
var table = $('#data').DataTable( {
ajax: "getdata.php"
});
and then:
setInterval( function () {
table.ajax.reload();
}, 10000 );
There are additional options you may want to pass in as arguments to the reload function depending on your use case. I hope this helps!
Upvotes: 1