How to redraw DataTable with new data

user2881063 picture user2881063 · Sep 19, 2014 · Viewed 150.1k times · Source

I have checked several questions already about this topic here in stackoverflow, but they are all using the old dataTable. I am using DataTable. I populated my DataTable by NOT USING server side, so data are preloaded (JSON) like this :

datatable = $("#datatable").DataTable({
   data  : myData,
   moreoptions : moreoptions
});

I didn't have a problem with that, the DataTable loaded just fine. Now I want to re-populate that myData with new data i uploaded. How to reload the DataTable to reflect the changes?

Here's what I have tried so far :

$('#upload-new-data').on('click', function () {
   myData = NewlyCreatedData; // I console logged this NewlyCreatedData, and it has my uploaded data.

   datatable.draw(); // Redraw the DataTable
});

But this doesn't work. I also tried this :

datatable = $("#datatable").DataTable({
   "data"  : myData,
   "drawCallback" : function () {
      myData = NewlyCreatedData;
   },
   "moreoptions" : moreoptions,
});

Then on upload I just call the redraw trigger :

$('#upload-new-data').on('click', function () {
   datatable.draw(); // Redraw the DataTable
});

Still this doesn't work.

Answer

SSA picture SSA · Sep 19, 2014

You have to first clear the table and then add new data using row.add() function. At last step adjust also column size so that table renders correctly.

$('#upload-new-data').on('click', function () {
   datatable.clear().draw();
   datatable.rows.add(NewlyCreatedData); // Add new data
   datatable.columns.adjust().draw(); // Redraw the DataTable
});

Also if you want to find a mapping between old and new datatable API functions bookmark this