How to Refresh a DataTable without Losing Your Current Page or Ordering CodeUnit 28 MAY 2012

DataTables is a fantastic plug-in for the jQuery Javascript library that I use for pretty much all my web development projects. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table – in other words, it creates useful dynamic, with oodles of extra functionality, tables out of plain old vanilla HTML tables.

Anyway, there is often a need to be able to refresh your datatable after applying some action to the source data, and the usual method of forcing a refresh is by calling the standard fnDraw() function on the table object. However, whilst this will redraw the table, it will basically reset you completely, removing any filtering and jumping back to page 1 if you have a table with pagination.

So not ideal.

Thankfully one of the DataTables forum guys came up with a handy bit of extension code which introduces a new function called fnStandingRedraw() which extends the datatables API and allows you to fresh the datatable without losing your current view.

To implement, simply put the following code into a .js file and load it after you load the standard datatables.js library:

$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
    //redraw to account for filtering and sorting
    // concept here is that (for client side) there is a row got inserted at the end (for an add)
    // or when a record was modified it could be in the middle of the table
    // that is probably not supposed to be there - due to filtering / sorting
    // so we need to re process filtering and sorting
    // BUT - if it is server side - then this should be handled by the server - so skip this step
    if(oSettings.oFeatures.bServerSide === false){
        var before = oSettings._iDisplayStart;
        //iDisplayStart has been reset to zero - so lets change it back
        oSettings._iDisplayStart = before;
    //draw the 'current' page

Now on your page code, you can simply ask for a refresh by doing this:

//var oTable1 = $('#mytable').dataTable();


Related Link:

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.