I have a scenario where I need to dynamically create a table by triggering a button click event.
function populateTable() {
$.ajax ({
url: 'php/GetData.php',
type: 'POST',
data: {id:25},
success: function(msg){
var obj = JSON.parse(msg);
var tableString = "<table id='tbla' class='display'><thead><tr><th>Name<th>Age<th>Birthday</tr></thead><tbody>";
for (var i=0; i<obj.length; i++) {
//alert(obj[i].name);
tableString += custom_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>", obj[i].name, obj[i].age, obj[i].birthday);
}
tableString += "</tbody></table>";
//alert(tableString);
$('#divb').html(tableString);
$('#tbla').dataTable();
}
});
}
The issue arises when trying to initialize the DataTable functionality using $('#tbla').dataTable();
. This fails because it's being called before the table with that ID is actually rendered on the page. How can this be resolved?
All necessary files such as CSS and JS for DataTables are properly included in the project.
<link rel="stylesheet" href="DataTables/dataTables.min.css"></style>
<script type="text/javascript" src="DataTables/dataTables.min.js"></script>
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}