How to update data tables

I use the DataTables plugin to make my table interactive.

The page displays echo'd PHP.

When I add a record to the database, I load the table using jQuery load (), but this interrupts the DataTables.

How to update a table while maintaining the integrity of DataTables?

Note. I use the DOM as a data source, not server side processing.

+8
jquery datatables
source share
3 answers

If you are performing a complete reload of the entire table, wrap the source code initialization source code in a function. Call this function when the page loads. When replacing a table completely with ajax, you should probably remove the parent table div, which is created by the plugin as a wrapper for all the table elements it creates without a table. If the table identifier = "example", the wrapper id = "example_wrapper".

There is enough code here, most likely it will suit you well. There are simple ways to only update rows, but since the request is to completely reload the table, I made sure that

function initDataTables(){ $('#myTable').datatables({/* put all current options here*/}) } /* within ready event of pageload */ $(function(){ initDataTables(); /* all other page load code*/ }); /* use $.get to reload table */ $.get( tableUpdateUrl, data, function( returnData){ $('#myTable').parent().replaceWith(returnData); /* re-initalize plugin*/ initDataTables(); }); 
+9
source share

When you create a data table, assign the resulting value to a variable:

 var table = $(".something").dataTable(); 

When you create your new element, presumably through AJAX, be sure to return the properties that your table should display. Then in your success function, you can use the fnAddData method to add a new row to your table. This method takes an array of values, the first in the first column, the second in the second, etc .:

 success: function(response){ table.fnAddData([ response.id, response.name, response.description, ]); } 

Read more about the fnAddData method here .

+5
source share

You should be able to use the ajax plugin. http://datatables.net/plug-ins/api

+1
source share

All Articles