jQuery DataTables: How to Reload a Table’s Data

Since my discovery of the awesome jQuery DataTables plug-in I haven’t stopped using it in my projects at it is by far the simplest and cleanest way of delivering feature-rich tables to a user.

Of course, I don’t usually work with static table data, meaning that I use server side processing scripts to load the data to my tables and when I started to employ user selectable data filters not connected to the DataTables object, I realised that I needed to be able to reload the DataTable’s data source at will.

However, simply trying to initialize a DataTable object on an existing DataTable object brings up the error message

DataTables warning: Unable to re-initialise DataTable. Please use the API to make any configuration changes required.

which is needless to say, a good indication that approach is not exactly going to get you anywhere.

The answer lies in exactly what the error message told you – you need to make use of the API calls on the existing DataTable in order to reload its data. So how to do this then?

Well essentially it is a pretty simple solution. First, we check if the known DataTables object exists, in other words, that it is not undefined. If it is undefined, initialize and draw it for the first time. If not, empty it first using the fnClearTable function and then redraw using the fnDraw function – which of course would then reload the updated dataset from the server side processing script.

if (typeof oTable == 'undefined') {
                        oTable = $('#commentstable').dataTable({
                                "bProcessing": true,
                                "bServerSide": true,
                                "iDisplayLength": 150,
                                "bLengthChange": false,
                                "sAjaxSource": "datatables_comments_list.php"
                        });
                }
                else
                {
                        oTable.fnClearTable( 0 );
                        oTable.fnDraw();
                }

Nice!

Related Link: http://datatables.net/index

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , . Bookmark the permalink.
  • http://www.datatables.net/ Allan Jardine

    Hi Craig,

    Nice write up – I’m enjoying your series of articles about DataTables! One thing to note about the reload, is that you shouldn’t need to call fnClearTable() since DataTables will effectively do this when fnDraw is called for server-side processing. It’s not much, but one line less of code :-)

    Regards,
    Allan
    .-= Allan Jardine´s last blog ..KeyTable 1.1.4 released =-.

  • http://www.datatables.net Allan Jardine

    Hi Craig,

    Nice write up – I’m enjoying your series of articles about DataTables! One thing to note about the reload, is that you shouldn’t need to call fnClearTable() since DataTables will effectively do this when fnDraw is called for server-side processing. It’s not much, but one line less of code :-)

    Regards,
    Allan
    .-= Allan Jardine´s last blog ..KeyTable 1.1.4 released =-.

  • http://www.craiglotter.co.za Craig Lotter

    @Allan: Ah, thanks for pointing that out. Didn’t know that, so went for the safer option of being more verbose in my thinking! :)
    .-= Craig´s last blog ..Failed Flash & Missing Backups =-.

  • https://codeunit.co.za Craig

    @Allan: Ah, thanks for pointing that out. Didn’t know that, so went for the safer option of being more verbose in my thinking! :)
    .-= Craig´s last blog ..Failed Flash & Missing Backups =-.

  • x2austin

    Craig, I am a total newbie to datatables but I have a need for them. I am using server-side table generation, through asp.net ajax. I get the table'(s) html back as a javascript variable(s).
    My question is very specific: how would I call the code you have listed above, using the javascript variable as a parameter.
    In other words, if I had a set of javascript variables that contained the html of different tables, how would I render any one of them optionally?
    Hope this makes sense..thanks.

  • http://twitter.com/craiglotter Craig Lotter

    I'm afraid I don't really know. I assume you would render the javascript variables first on the page, and then rebind the datatables initialization code to the newly rendered DOM objects once these tables have been rendered.

  • xyz

    when FnDeleteRow is used is the row removed from datatable or is it hidden???

  • http://www.craiglotter.co.za Craig Lotter

    As far as I understand, the actual row will be removed from the DOM. You would have to reinstantiate to get it back

  • Bronco

    Thanx Man!! Helps a lot and saves time!
    Frank

  • Ben

    To anybody searching and finds this: Craig your page really helped me nail this, I use AJAX w/ arrays and Asp.net with c#, my code looks like this:

    var table;
    function generate_report(){
    $.ajax({
    type: ‘POST’,
    url: ‘WebServices/DashboardService.asmx/report’,
    contentType: ‘application/json; charset=utf-8′,
    dataType: ‘{}’,
    data: JSON.stringify({ “dateSpec”: document.getElementById(”).value
    }),
    dataFilter: function(data) {
    var msg;

    if (typeof (JSON) !== ‘undefined’ &&
    typeof (JSON.parse) === ‘function’)
    msg = JSON.parse(data);
    else
    msg = eval(‘(‘ + data + ‘)’);

    if (msg.hasOwnProperty(‘d’))
    return msg.d;
    else
    return msg;
    },
    success: function(data) {
    if(typeof table == ‘undefined’){
    table=$(‘#report_table’).dataTable({
    “bDestroy”: true,
    “bPaginate”: false,
    “bLengthChange”: false,
    “bFilter”: false,
    “bInfo”: false,
    “bAutoWidth”: false,
    “bJQueryUI”: true,
    “sScrollY”: 170,
    “sScrollX”: “100%”,
    ‘aaData’: data,
    “aoColumns”: [
    { "sTitle": "col1" },
    { "sTitle": "col2" }
    ],
    “sDom”: ‘Tlfrtip’
    });
    }else{
    table.fnClearTable(0);
    table.fnAddData(data);
    table.fnDraw();
    }
    }
    });
    }
    $(document).ready(function() {
    generate_report();
    });

    (the key difference between his is instead of just calling draw() you have to call addData()

  • Jakethesnakeiiiii

    how’s the job market in SA?

blog comments powered by Disqus