120

I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:

var myData = [
    {
        "id": 1,
        "first_name": "John",
        "last_name": "Doe"
    }
];

$('#table').dataTable({
    data: myData
        columns: [
        { data: 'id' },
        { data: 'first_name' },
        { data: 'last_name' }
    ]
});

Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.

Indy
  • 4,838
  • 7
  • 24
  • 35

6 Answers6

212

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).

CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:

  1. The modern definition of DataTables (upper camel case):

    var datatable = $( selector ).DataTable();

  2. The legacy definition of DataTables (lower camel case):

    var datatable = $( selector ).dataTable().api();

  3. Using the new syntax.

    var datatable = new $.fn.dataTable.Api( selector );

Then load the data like so:

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Use draw(false) to stay on the same page after the data update.

API references:

https://datatables.net/reference/api/clear()

https://datatables.net/reference/api/rows.add()

https://datatables.net/reference/api/draw()

Richard
  • 56,349
  • 34
  • 180
  • 251
Indy
  • 4,838
  • 7
  • 24
  • 35
  • 5
    This was too hard to find, many thanks! Using this to persist the datatable between server roundtrips. – Doug Oct 26 '17 at 14:53
  • What about datatables version 1.9.4 I am facing same problem in that – Hardik Masalawala Jun 06 '18 at 13:41
  • 9
    I just want to add that you can also chain the methods (i.e. `datatable.clear().rows.add(newDataArray).draw()`). As of this comment, I am using version 1.10.18 – Molasses Feb 22 '19 at 22:10
  • 1
    For once a simple and crystal clear solution about the DataTAbles API!!! Kudos, well done. You saved my day – user3553401 Jun 28 '22 at 14:10
38

You can use:

$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);

Jsfiddle

Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

Vladimirs
  • 8,232
  • 4
  • 43
  • 79
14

You need to destroy old data-table instance and then re-initialize data-table

First Check if data-table instance exist by using $.fn.dataTable.isDataTable

if exist then destroy it and then create new instance like this

    if ($.fn.dataTable.isDataTable('#dataTableExample')) {
        $('#dataTableExample').DataTable().destroy();
    }

    $('#dataTableExample').DataTable({
        responsive: true,
        destroy: true
    });
Om Prakash Sharma
  • 1,682
  • 22
  • 13
7

Here is solution for legacy datatable 1.9.4

    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);
Vikas
  • 91
  • 1
  • 3
  • This works for recent version (please, consider the date of the comment). Thank you Vikas! – Telmo Mar 29 '19 at 21:14
  • This worked for me. But I don't understand why I can use all these examples: var datatable = $( selector ).DataTable(); var datatable = $( selector ).dataTable().api(); var datatable = new $.fn.dataTable.Api( selector ); But when adding .row().add() doesn't work. – fp007 Apr 08 '20 at 13:51
6

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).

My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).

Then I instantiate my table in the on load method

$(function () {
            //.... some code here
            table = $("#detailReportTable").DataTable();
            .... more code here
        });

and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:

function getOrderDetail() {
            table.clear();
            table.destroy();
            ...
            $.ajax({
             //.....api call here
            });
            ....
            table = $("#detailReportTable").DataTable();
   }

I hope someone finds this useful!

jorge cordero
  • 91
  • 1
  • 3
  • 2
    Destroying the whole table at every roundtrip is rather expensive and the state is lost also. You should consider the accepted answer where the state of the table is kept. – nhaberl Mar 16 '18 at 12:49
0

I know my answer is not directly related to the question, but I spend a lot of time on finding the way to do the same thing in the newer version of datatables, so I hope my example will save somebody's time in the future

const table = js('#tbllist').DataTable({
    columns: [
        {data: 'createDate'},
        {data: 'status'},
        {data: 'paymentType'},
        {data: 'currency'},
        {data: 'amount'}
    ]
});

// Assume that this array has objects of new data with structure defined above
const arr = [] 

// These will update table
table.clear();
table.rows.add(arr);
table.draw();