Refreshing data in jQuery DataTables

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

<table id="HelpdeskOverview">
  <thead>
    <tr>
      <th>Ärende</th>
      <th>Rapporterad</th>
      <th>Syst/Utr/Appl</th>
      <th>Prio</th>
      <th>Rubrik</th>
      <th>Status</th>
      <th>Ägare</th>
    </tr>
  </thead>
  <tbody> 
  </tbody> 
</table>
function InitOverviewDataTable() {
    oOverviewTable = $('#HelpdeskOverview').dataTable(
        {
            bPaginate: true,
            bJQueryUI: true, // ThemeRoller-stöd
            bLengthChange: false,
            bFilter: false,
            bSort: false,
            bInfo: true,
            bAutoWidth: true,
            bProcessing: true,
            iDisplayLength: 10,
            sAjaxSource: '/Helpdesk/ActiveCases/noacceptancetest',
            fnRowCallback: formatRow
        });
}
function RefreshTable(tableId, urlData) {
    //oSettings.sAjaxSource?
    $.getJSON(urlData,
        null, function (json) {
            table = $(tableId).dataTable();
            oSettings = table.fnSettings();

            table.fnClearTable(this);
            for (var i = 0; i < json.aaData.length; i++) {
                table.oApi._fnAddData(oSettings, json.aaData[i]);
            }
            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
            table.fnDraw();
        });
}
function AutoReload() {
    RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

    setTimeout(function () { AutoReload(); }, 30000);
}
$(document).ready(function () {
    InitOverviewDataTable();
    setTimeout(function () {
           AutoReload();
        },
        30000);
});

31 thoughts on “Refreshing data in jQuery DataTables”

  1. Agree! Curiously difficult is the word!

    To refresh a jqGrid table is a “one-liner”:

    $(tableId).jqGrid(‘setGridParam’, { url: urlData}).trigger(“reloadGrid”);

    I personally like jqGrid better. It is more powerful and feature-rich. And I have heard it has better performance (but that I don’t know). On the other hand DataTables is simpler to learn – but not for this apparently 🙂

    http://www.trirand.com/blog/
    Demos at
    http://www.trirand.com/blog/jqgrid/jqgrid.html

  2. Yes, but for some reason that did not work for me. When googling I found several others having the same problem and that’s why I wrote this post. Apparently it’s some combination of configuration options that causes the problems…

    Thanks for the comment though, it may very well work for others having similar problems.

  3. OMG i was breaking my head on a wall for 2 days, copy pasted your code and modified the table name along with the ajax source and it worked right out of the box on my rails 3 app

  4. Hej Emil,

    Your implementation looks great but how can I send custom data to the server along with the refresh request?

    I mean, something like this for example:
    “fnServerParams”: function ( aoData ) {
    aoData.push({“name” : “id”, “value” : ${param.id}});}

    Thanks.

  5. Firstly Thank you for writing this function,

    I am writing a CGI file to load datatable , But when I am calling AutoReload() on mouse click to refresh the table, nothing happening. Am I doing something wrong?

    Thanks

  6. Hi @Shahid ,

    I’m afraid it’s very difficult to know what your problem is, all I know is that the above code works for me. I can only assume that you have copied something wrong or missed to replace an id or something like that. Have you had a look at your browser’s script console? Any errors that occur should be displayed there.

    /Emil

  7. Thanks Emil for your reply,

    I tried debugging code and couldn’t solve it. ended up using their API to reload Ajax source. I am good not. thanks for your help though.

  8. @Leo

    this send parameters to server using post and shows progress

    oSettings = table.fnSettings();

    $(‘.dataTables_processing’).css(‘visibility’,’visible’).show();

    $.post(oSettings.sAjaxSource, {state:0}, function( json ){
    table.fnClearTable(this);
    for (var i=0; i<json.aaData.length; i++){
    table.oApi._fnAddData(oSettings, json.aaData[i]);
    }
    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
    },'json')
    .always(function(){$('.dataTables_processing').hide();});

  9. Mad props to you Emil, you really helped me out.
    I’d like to add just the following:
    If you’re using jQuery instead of $ just add jQuery.noConflict() at the beggining of your javascript code; then replace $ by jQuery, as it is shown below:

    function RefreshTable(tableId, urlData)
    {
    jQuery.getJSON(urlData, null, function( json )
    {
    table = jQuery(tableId).dataTable();
    oSettings = table.fnSettings();

    table.fnClearTable(this);

    for (var i=0; i<json.aaData.length; i++)
    {
    table.oApi._fnAddData(oSettings, json.aaData[i]);
    }

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
    });
    }

  10. Hi Emil,

    I tried your solution, its worked perfectly 🙂 .
    Thanks for your wonderful article on DataTable refresh.

    Regards,
    Preetam

  11. because I get this error:

    Cannot read property ‘length’ of undefined

  12. Hi Emil,

    I just wanted to thank you for providing this solution. I have been working with dataTables for a while and could not find a proper description on the dataTables API.

    Just used your code adapted to my table and…boom. It worked where any other single try failed.
    I think fnSettings() and fnClear() were the key. Although I do not fancy the idea of clearing the whole table to just update a single change (for big data sets this might not be the best solution), I am completely satisfied with this feature working. It will be time to improve it 🙂

    Thank SO much.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.