123

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.

1
  • How about deleting the existing tablebody and create it new? Commented Jan 5, 2015 at 11:20

6 Answers 6

218

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()

Sign up to request clarification or add additional context in comments.

6 Comments

This was too hard to find, many thanks! Using this to persist the datatable between server roundtrips.
What about datatables version 1.9.4 I am facing same problem in that
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
For once a simple and crystal clear solution about the DataTAbles API!!! Kudos, well done. You saved my day🙂
Great answer. I have a different problem though: how do you do this with polling? If you're constantly getting new data, how can you keep the table intact - paging for instance. So if the user is on page 2, clearing the data and redrawing resets them back to page 1.
|
40

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.

3 Comments

Yes, you're right, but I'm using the latest version of datatables. Anyway, I found a solution and updated my question. Thanks for your interest :)
@CookieMan, please remove your edit and post it as an answer. After that, mark it as accepted.
this solution is not updating pagination section
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
    });

Comments

8

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);

2 Comments

This works for recent version (please, consider the date of the comment). Thank you Vikas!
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.
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!

1 Comment

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.
1

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.