I am using DataTables plugin to make my table interactive.
The table is echo'd by PHP on the page.
When I add a record to the DB I am loading the table using jQuery load() but this breaks DataTables.
How can I update the table while still keeping DataTables Intact?
Note: I am using DOM as the data source and not server side processing.
A table displays data, usually from a query - if you want to reload the query you can . trigger() it from any script, or another component (like a custom button) or the refresh button option in the table component will do this for you.
function clear() Simply remove all rows of data from the table.
If doing a complete reload of the whole table, wrap your initial datatables initialization code in a function. Call that function on page load. When replacing the table completely with ajax you likely should remove the table parent div that is created by plugin as a wrapper for all the non table DOm elements it creates. If table ID="example" , wrapper id="example_wrapper".
Here's enough code will likely get you well on your way. There are easy ways to only update rows but since request is for a complete table reload I've followed 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();
});
When you create your data table, assign the resulting value into a variable:
var table = $(".something").dataTable();
When you create your new item, presumably via AJAX, make sure to return the properties that your table needs to display. Then, in your success
function, you can make use of the fnAddData
method to add a new row to your table. This method takes in an array of values, the first one goes in the first column, second in second, and so on:
success: function(response){
table.fnAddData([
response.id,
response.name,
response.description,
]);
}
You can read more about the fnAddData
method here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With