Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh DataTables

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.

like image 521
Billy Martin Avatar asked Mar 12 '12 20:03

Billy Martin


People also ask

How do you refresh a table in Javascript?

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.

How do I empty a DataTable?

function clear() Simply remove all rows of data from the table.


2 Answers

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();
}); 
like image 126
charlietfl Avatar answered Oct 08 '22 01:10

charlietfl


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.

like image 26
Mike Trpcic Avatar answered Oct 08 '22 01:10

Mike Trpcic