I'm dynamically creating my datatable and HTML table. It works perefectly fine until the column no is same. But it doesn't update properly once the no.of columns changes.
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 columns instead create a new Datatable with column headers from previous three-column table with an error in console:
Cannot read property 'sWidth' of undefined
I tried to destroy table but it doesn't update:
$('#tblActivitySummary').DataTable().destroy();
$('#tblActivitySummary').dataTable().fnClearTable();
$('#tblActivitySummary').empty();
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).empty();
$(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 the it doesn't update the column headers. Why wouldn't it clear previous datatable columns? Is this happening because I'm creating different columns on same table? Please help