I'm using KTDatatable for reference "https://ktui.io/docs/datatable#basic-usage".
But, I don't know how to refresh data in KTDatatable by local information.
Can I refresh KTDatatable with JSON or dynamic rendered local HTML?
Hi
Can you try this? KTDatatable to re-read the table content by invalidating its internal state
function updateDatatable() {
const datatableEl = document.querySelector("[data-kt-datatable='true']");
const tbody = datatableEl.querySelector('tbody');
// Add your new row
idCounter += 1;
tbody.insertAdjacentHTML("beforeend", `
${idCounter}
TEST_NAME_${idCounter}
`);
// Get the datatable instance
const datatable = KTDataTable.getInstance(datatableEl);
// Force content invalidation by clearing the content checksum
datatable.getState()._contentChecksum = null;
// Reload the datatable
datatable.reload();
}
here is my simple demo code. but it doesn't work. what's wrong with my code?
ID
NAME
1
TEST_NAME_1
<script>
document.addEventListener('DOMContentLoaded', function () {
initDatatable();
});
function initDatatable() {
KTDataTable.init();
KTDataTable.createInstances();
const datatableEl = document.querySelector('#kt-datatable-div');
const datatable = KTDataTable.getInstance(datatableEl);
datatable.reload();
console.log("initialized");
console.log(datatable.getState()); // originalData is empty
}
let idCounter = 1;
function updateDatatable() {
const datatableEl = document.querySelector('#kt-datatable-div');
const b = datatableEl.getElementsByTagName('tbody')[0];
idCounter += 1;
b.insertAdjacentHTML('beforeend', `<tr>
<td>${idCounter}</td>
<td>TEST_NAME_${idCounter}</td></tr>`);
const datatable = KTDataTable.getInstance(datatableEl);
datatable.reload();
console.log(datatable.getState()); // also originalData is empty
}
</script>
Hi
KTDatatable provides several methods to refresh data with local information. Here are the main approaches.
For local data, you can use the reload() method which will re-fetch data from the DOM:
// Get the datatable instance
const tableElement = document.querySelector("#your_table_id");
const dataTable = KTDataTable.getInstance(tableElement);
// Update the table HTML with new data first
// Then reload the datatable
dataTable.reload();