[jquery] Redraw datatables after using ajax to refresh the table content?

I am using Datatables and have a button on the page that refreshes the table using AJAX. To be clear the table isn't using an ajax source of data, we are just using ajax to refresh it only when needed. Ajax is refreshing the div which the table is wrapped in. I know i'm losing my pagination buttons and filtering capability because the table needs to be redrawn but i'm not sure how to add this into the table initialization code.

Datatables code

var oTable6;
$(document).ready(function() {
    oTable6 = $('#rankings').dataTable( {
        "sDom":'t<"bottom"filp><"clear">',
        "bAutoWidth": false,
        "sPaginationType": "full_numbers",
        "aoColumns": [ 
            { "bSortable": false, "sWidth": "10px" },
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ]

    });
});

The ajax code is this

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
        function( data ) { 
            $("#ajaxresponse").html(data);
        });
});

I tried this but it didn't work

"fnDrawCallback": function() {
    function( data ) { 
        $("#ajaxresponse").html(data);
    };
},

This question is related to jquery ajax datatables

The answer is


Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);

This works for me

var dataTable = $('#HelpdeskOverview').dataTable();

var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
   dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.


This is how I feed my table with data retrieved by ajax (not sure if this is the best practice tough, but it feels intuitive and works well):

/* initialise table */
oTable1 = $( '.tables table' ).dataTable
( {
    'sPaginationType': 'full_numbers',
    'bLengthChange': false,
    'aaData': [],
    'aoColumns': [{"sTitle": "Tables"}],
    'bAutoWidth': true
} );


 /*retrieve data*/
function getArr( conf_csv_path )
{
    $.ajax
    ({
        url  : 'my_url'
        success  : function( obj ) 
        {
            update_table( obj );
        }
    });
}


/* build table data */
function update_table( arr )
{        
    oTable1.fnClearTable();
    for ( input in arr )
    {
        oTable1.fnAddData( [ arr[input] );
    }                                
}

Try destroying the datatable with bDestroy:true like this:

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
            function( data ) { 

                $("#ajaxresponse").html(data);

                oTable6 = $('#rankings').dataTable( {"bDestroy":true,
                    "sDom":'t<"bottom"filp><"clear">',
                    "bAutoWidth": false,
                    "sPaginationType": "full_numbers",
"aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

} 
);
            });

});

bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.


I'm not sure why. But

oTable6.fnDraw();

Works for me. I put it in the next line.


In the initialization use:

"fnServerData": function ( sSource, aoData, fnCallback ) {
                    //* Add some extra data to the sender *
                    newData = aoData;
                    newData.push({ "name": "key", "value": $('#value').val() });

                    $.getJSON( sSource, newData, function (json) {
                        //* Do whatever additional processing you want on the callback, then tell DataTables *
                        fnCallback(json);
                    } );
                },

And then just use:

$("#table_id").dataTable().fnDraw();

The important thing in the fnServerData is:

    newData = aoData;
    newData.push({ "name": "key", "value": $('#value').val() });

if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.


check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to datatables

Datatables Select All Checkbox DataTables: Cannot read property style of undefined How do I filter date range in DataTables? DataTables: Cannot read property 'length' of undefined TypeError: $(...).DataTable is not a function jQuery DataTables Getting selected row values How to manually update datatables table with new JSON data DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined How to redraw DataTable with new data Datatables: Cannot read property 'mData' of undefined