How to refresh DataTable column headers

How to refresh DataTable column headers

RamDziRamDzi Posts: 2Questions: 2Answers: 0
edited January 2017 in Free community support

I'm dynamically creating my datatable and HTML table. It works perefectly fine until the column numbers are same. But it doesn't update column headers when I call it again with different number of columns.

First time, the no.of columns is three, it creates three column table on tblActivitySummary but when I call LoadGrid _again with new data in _object.ActivitySummary which has two columns, it doesn't update column headers, creates a new Datatable with previous three-columns with an error in console:

Cannot read property 'sWidth' of undefined

I tried to destroy table like this but to no avail:

$('#tblActivitySummary').DataTable().destroy();
$('#tblActivitySummary').dataTable().fnClearTable();

Here is the ajax

$.ajax({
    data: JSON.stringify(data),
    url: urlGetRGUStatusReportData,
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    success: function (obj) {
        var object = jQuery.parseJSON(obj.data);
        LoadGrid("#tblActivitySummary", object.ActivitySummary, object.ColumnNamesActivitySummary, false);
});

Here is how I'm creating DataTable:

function LoadGrid(tableId, gridData, displayColumnNames, IsSearchable) {
    var columnKeys = [];

    for (var k in gridData[0]) {
        columnKeys.push({ "data": k });
    }

    CreateHTMLTable(tableId, displayColumnNames); //Create table dynamically

    $(tableId).DataTable().destroy();
    $(tableId).dataTable().fnClearTable();
    $(tableId).dataTable({
        "searching": IsSearchable,
        "bDestroy": true,
        "scrollY": 450,
        "scrollX": true,
        data: gridData,
        columns: columnKeys
    });
}

Creating **HTML **table

function CreateHTMLTable(tableId, displayColumnNames) {
    var columnNames = [];
    for (var k in displayColumnNames[0]) {
        columnNames.push(k);
    }
    var $toAttach = $("<thead><tr></tr></thead>");

    for (var i = 0; i < columnNames.length; i++) {
        var $thead = $("<th></th>");
        $thead.text(columnNames[i]);
        $toAttach.find("tr").append($thead);
    }
    $(tableId).append($toAttach);
}

Though it updates the data in it but it doesn't update the column headers. Why wouldn't it clear previous datatable column headers? Is this happening because I'm creating different columns on same table? Please help

This discussion has been closed.