Datatables refresh with draw(), ajax, pagination

Heinrich picture Heinrich · Jul 7, 2015 · Viewed 9.3k times · Source

I'm trying to refresh my table with data from the server every few seconds. It's loading the new data but the pagination is not working at all. By that I mean, it's one big list of the data. It's also saying Showing 0 to 0 of 0 entries (filtered from NaN total entries) for the pagination at the bottom of the table.

I am using draw(false) in a setInterval function to achieve the refresh. I wanted to do this without using "serverSide":"true" but I found that draw() doesn't call the ajax url unless I use the serverSide option.

function myFunction() { 
var table1 = $("#example1").dataTable({
    "ajax": '/api/GetData',
    "serverSide": "true",
    "columns": [
        {
            "data": "DateCreated",                
        },
        { "data": "UserName" }
    ],
    "destroy": true
});

setInterval(function test() {        
    table1.draw(false);
}, 3000);
}

When I omit "serverSide":"true" the table is drawn correctly with the pagination but the ajax is not called with draw(). How can I get the ajax data and have the pagination set correctly?

Answer

Gyrocode.com picture Gyrocode.com · Jul 7, 2015

Use ajax.reload() to reload the table data from the Ajax data source with false as a second parameter to avoid resetting current paging position.

table1.api().ajax.reload(null, false);

Since your table is initialized using dataTable(), API methods can be accessed with table1.api() method. Otherwise, if table is initialized using DataTable(), API methods can be accessed using table1 directly. See DataTables API for more information.