How to manually update datatables table with new JSON data
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.
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:
The modern definition of DataTables (upper camel case):
var datatable = $( selector ).DataTable();
The legacy definition of DataTables (lower camel case):
var datatable = $( selector ).dataTable().api();
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()
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);
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
});