jQuery DataTables: How to Reload a Table’s Data CodeUnit 24 MAR 2010

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

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.

  • 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 =-.

  • 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 =-.

  • @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 =-.

  • @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.

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

  • 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???

  • 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

  • Jakethesnakeiiiii

    how’s the job market in SA?

  • This post is really helpful for me.

  • I got great informative Its use full Thank for sharing this site

  • Rodolfo Jorge Nemer Nogueira

    Thanx Man!! Helps a lot and saves time!
    Rodolfo Jorge Nemer Nogueira

  • masterpra

    Hi, nice all ur articles … HOw to handle sub-row from a row datatable (like sub-grid in JQGrid)? …I am codeigniterian level 1 :) … thank you for advice …masterpra2002@yahoo.com

  • Velociraptor

    Thanks a lot!

  • Thanks for this post. BTW, you can do this with one line, oTable.fnClearTable(true). The parameter is redraw the table or not http://datatables.net/api.

  • Hello, i just come here to say thank’s for sharing your knowledge!

  • Have you somehow managed also to chnage dynamically the headers and footers of the table basing on the content delivered from serverside? For now only way I managed to get this effect is by destroying and newly reinitialzing the table…

  • Priti

    Thanks! It also works for me.

  • Gavin

    Hi Hoping someone can assist me I have the below call that renders a checkbox contol in my DataTable Grid as well as “stateSave”: true, But for some reason when paging I loose the value of the control eg checked would then reflect as unchecked.

    ‘mRender’: function (data, type, row) {
    return “”
    }