destroy table and reinitialize
destroy table and reinitialize
Hello together,
I need some help using datatables. Loading a datatable works fine. But now I have to change data inside the table. I learned , that once a table is initialised, it is not possible to change data so easy.
The html code:
<table id="tableId" class="table table-striped display text-right" role="grid" style="width: 100%">
My javascript code is:
$(tableId).DataTable(data);
Filling the table works fine. But with updating the table, I get following error:
DataTables warning: table id=tableId- Cannot reinitialise DataTable. For more information about this error, please see
http://datatables.net/tn/3
I tried to look for an answer. So far I found something about destroy() but nothing works. I guess it is a simple solution, but... How can I clear the whole table and reinizialise it with new data.
I tried following (found here in the forum):
let table = document.getElementById(tableId);
// clear first
if(table!=null){
table.clear();
table.destroy();
}
//2nd empty html
$(tableId + " tbody").empty();
$(tableId + " thead").empty();
//3rd reCreate Datatable object
$(tableId).DataTable(data);
But I always get the above failure message.
Would be happy for some help
This question has accepted answers - jump to:
Answers
So how are you updating the table?
I thought I can reinitialise the data or better fill the data again with:
$(tableId).DataTable(data);
I am looking for a way, to dump all data in the table and fill the empty table with new data. It works as long as I reload the whole page. But I would like to change the data in the table without reloading.
You only need to destroy and reinitialize the Datatable if you are changing the configuration. Otherwise you can use
clear()
to clear the Datatable then userows.add()
to add new rows. If you are usingajax`` you might be able to use
-api ajax.reload()` to reload the data. FOr more specific help please answer Tangerine's questions so we know how you are updating the table.Kevin
I don't see my mistake... There must be a mistake in the if() part. The else part works. Happy for some help
I use following code:
The object data.data looks like:
The object data looks like:
The failure message:
DataTables warning: table id=XXXX- Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
Use
$.fn.dataTable.isDataTable()
to check of the table is a Datatable instead oftable!=null
. Not sure why but it seems this test always fails and uses the else clause causing theCannot reinitialise DataTable
error when trying to reload.Kevin
Also you need to use
draw()
withrows.add()
, for exampletable.rows.add(data.data).draw();
. See the docs for more details.Kevin
Thanks a lot for your help Kevin,
I got it to work!
@harald What is your updated code?