This is admittedly a JS question rather than a DataTables proper question, but I'm turning to the most intelligent, handsome, and friendliest bunch of programmers I know before heading to the callous lion's den of stackoverflow :-)
I have a DataTable that I want to populate with data from a JS object that is the result of a previous jQuery ajax call.
Using this basic example:
https://datatables.net/examples/data_sources/js_array.html
I'm setting it up this way:
var dataSet;
$.ajax({
type: "GET",
url: "datafile.php",
dataType: "json",
success: function (data) {
dataSet = data;
}
});
$(document).ready(function () {
$('#example').DataTable({
data: dataSet,
columns: [
{title: "Name"},
{title: "Position"},
{title: "Office"},
{title: "Extn."},
{title: "Start date"},
{title: "Salary"}
]
});
});
However dataSet
is undefined when the DataTable is created.
I'm certain it's an asynchronous timing issue because I'm initializing the DataTable before the variable "dataSet" has been returned, but any suggestions on how I should structure this?
=== Just extra explanation ==
My actual case involves returning a JS object with multiple data sets, each of which will be used in a table of its own, so that's why I'm trying this route instead of using the ajax request from DataTables itself.
Basically:
var dataSet;
$.ajax({
type: "GET",
url: "datafile.php",
dataType: "json",
success: function (data) {
dataSet = data;
// Looks like dataSet.staff, dataSet.locations, dataSet.titles, etc.
}
});
$(document).ready(function () {
$('#staffTable').DataTable({
data: dataSet.staff,
columns: [
...
]
});
$('#locationsTable').DataTable({
data: dataSet.locations,
columns: [
...
]
});
$('#titlesTable').DataTable({
data: dataSet.titles,
columns: [
...
]
});
});