reinitialize DataTable with new columns

reinitialize DataTable with new columns

ludwigmludwigm Posts: 12Questions: 8Answers: 1

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

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    The code isn't showing how the columns are added/removed from the HTML, before the DataTable is re-initialised.

    We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. 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.

    Colin

  • kthorngrenkthorngren Posts: 21,289Questions: 26Answers: 4,943
    Answer ✓

    You might need to use jQuery empty() as shown in the destroy() docs to remove the HTML table when changing the number of columns.

    Kevin

Sign In or Register to comment.