PHP User PHP User - 1 year ago 183
Ajax Question

redraw datatable after ajax call

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 () {

$( "#orderdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: '2013:2050',

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() !== '' ) {
//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


$('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?

Answer Source

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(); // user paging is not reset on 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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download