datatable refresh/reload with new data
datatable refresh/reload with new data
vicdave
Posts: 2Questions: 0Answers: 0
Sample code below will load a datatable with pagination, search, sort properly the first time. When I try to call it again with new data it will load the data in a datatable with the controls but they won't work. I can't search or sort and the pagination doesn't work and it shows the data in one page. How can I get the controls to work properly when datatable is refresh/reloaded with new data?
Thank you
function loadBootStrapTable(data) {
try {
if (!isFirstLoad) {
isFirstLoad = false;
let t = $('#dataTableId').DataTable();
t.rows().remove().draw(true);
}
let col = [];
let table = document.getElementById("dataTableId");
table.innerHTML = "";
table.style.visibility = "visible";
let header = table.createTHead();
let tr = header.insertRow(0);
for (let key in data[0]) {
let th = document.createElement("th");
th.innerHTML = key;
tr.appendChild(th);
col.push(key);
}
let body = table.createTBody();
for (let i = 0; i < data.length; i++) {
let tr = body.insertRow(0)
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(j);
tabCell.innerHTML = data[i][col[j]];
}
}
if (true) {
isFirstLoad = false;
let t = $(document).ready(function () {
$('#dataTableId').DataTable();
});
t.draw();
}
else {
let t = $('#dataTableId').DataTable();
t.draw(true);
}
}
catch (e) {
console.log(e.toString());
}
}
This discussion has been closed.
Replies
Hi @vicdave ,
There's a few odd things there:
1.looks like you drawing the page
you don't need to draw after initialising it.
the code on line 41 won't reinitialise the table, it will just return an object for the existing DataTable. You can either
destroy()
(ordestroy
) to force a recreate, or you can invalidate all the rows withrows().invalidate()
to force a refreshHope that works, if not, could you create a test case demonstrating the problem, please. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
Thanks Colin.
Destroy() works nicely for this situation. I couldn't get rows().invalidate() to work. New cleaned up code below. Curious how I can check if DataTable is initialized? I'm using a variable (isFirstLoad) currently, but would like to get rid of it. I've tried numerous things but they didn't work.
Hi @vicdave ,
Glad all making progress. You can check if the table is initialised with
$.fn.dataTable.isDataTable()
,Cheers,
Colin