Using array of objects JSON as a data source
Using array of objects JSON as a data source
Hi all. DataTables novice, so thank you in advance to anyone that can assist me. My head is swimming right now from trying to find my answer in an example. How can I use an array of objects from AJAX as a data source?
Right now, I'm calling a PHP page, which is doing a json_encode at the end. I've verified that it is valid JSON, in the following format:
[
{
"MONTH":"1",
"TIME":"15:00",
"TEXT":"Blah"
},
{
"MONTH":"1",
"TIME":"14:21",
"TEXT":"Blah2"
},
...
]
The only way I've made a valid DataTable with this data is to convert it into a 2-D Array. Which works, but doesn't seem like the best way to go about things. My Javascript is shown below:
$.ajax({
type: "GET",
url: '/test.php',
dataType: 'json',
success: function (obj, textstatus) {
var dataSet = new Array;
if (!('error' in obj)) {
$.each(obj, function (index, value) {
var tempArray = new Array;
for (var o in value) {
tempArray.push(value[o]);
}
dataSet.push(tempArray);
})
$('#example2').DataTable({
data: dataSet,
columns: [
{ title: "Month" },
{ title: "Time" },
{ title: "Text" }
]
});
}
else {
alert(obj.error);
}
},
error: function (obj, textstatus) {
alert(obj.msg);
}
});
I was initially looking at doing this server side, but that whole setup was going over my head, so I just tried to get a data object. Any help would be appreciated.
This question has accepted answers - jump to:
Answers
Datatables expects JSON to be wrapped inside a
data:
object by default, however, you can callajax.datasrc
and use an empty string in order to use a custom flat array, take a look a this exampleThanks
Tom
Another thing is inside your initialisation you should be using
columns.data
and then depending on if you have column headers in your html you can use title.You should be able to cut down that code to this
You can take a look at the documentation on using objects here
Thanks
Tom
Tom, thank you so much!!