kevinabraham kevinabraham - 1 month ago 21
Ajax Question

How to convert a dynamic table to a jquery data table?

I am dynamically creating a HTML table from json data. I then want to convert this table to a datatable. But when I try to do this I keep getting an error that reads:

Uncaught TypeError: Cannot read property 'mData' of undefined


My jquery is:

$(document).ready(function() {
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson.com/bins/1oaye',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}

// CREATE DYNAMIC TABLE.
var table = document.createElement("table");


// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

var tr = table.insertRow(-1); // TABLE ROW.

for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}

// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < data.length; i++) {

tr = table.insertRow(-1);

for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}

// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);

// convert it to a data table
table.setAttribute("id", "example");
$('#example').DataTable();

},
type: 'GET'
});
});
});


How do I create or convert a dynamic table to a data table from json?

JSFiddle showing the issue

Answer

Just having a quick look at the DataTable code and it looks like the likely reason is that you haven't put the <th> in a <thead> section. Currently they sit within <tbody>.

Here's the updated fiddle... https://jsfiddle.net/8some9a0/1/

Comments