I like to create (if not exists) or update a DataTable. There are two cases with the update:
- The columns remain the same and only the rows are to be updated
- Columns and rows are to be updated (a different data basis) The distinction between creating and updating already works.
So far I have this code:
if ($.fn.dataTable.isDataTable(table_id)) {
let datatable = $(table_id).DataTable();
// Get the column names of the existing DataTable
let existingColumnNames = datatable.columns().header().toArray().map(header => $(header).text());
// Check if the existing column names match the column names of the new data
let columnNamesMatch = JSON.stringify(existingColumnNames) === JSON.stringify(columnNames);
if (columnNamesMatch) {
// Only rows need to be updated
datatable.clear();
datatable.rows.add(new_data);
datatable.draw('full-hold'); // keep current page
} else {
// Both columns and rows need to be updated
datatable.clear();
datatable.destroy(); // Destroy the existing DataTable
$(table_id).DataTable({
data: new_data,
columns: columns_array
});
}
} else {
$(table_id).DataTable({
data: new_data,
columns: columns_array
});
}
In most cases it works. However, if the number of columns in the existing table is greater than that of the new table, an error occurs: Uncaught TypeError: oCol is undefined In the header row, the new column names on the left and col_new - col_old number column names of the previous table are displayed. So the header does not seem to be completely removed by datatable.destroy()? The new_data is fetched by AJAX and returned as JSON.
Debugger code: oroqud
Database test case: db-fiddle