Error loading JSON object into Datatable JQuery
I am using DataTables
with Jquery
, I have an object data object JSON
that I want to get through Ajax
and appear in a table.
JSON
data is returned from url /live/log
and formatted like this:
{
"Logs": [
{
"date": "2015-04-22T14:00:39.086Z",
"eventType": "event1",
"str": "Application startup"
},
{
"date": "2015-04-22T14:01:27.839Z",
"eventType": "event2",
"str": "test Logged in"
}
]
}
My HTML table:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Event</th>
<th>Description</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date</th>
<th>Event</th>
<th>Description</th>
</tr>
</tfoot>
</table>
And finally the JS for fetching and populating data:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "/live/log",
"columns": [
{"data": "date"},
{"data": "eventType"},
{"data": "str"}
]
});
});
I can see through the debugger the data is being JSON
retrieved correctly.
I seem to have gotten an error in DataTables
js related to data JSON
.
Value aData in fnInitalise is null - Uncaught TypeError: Cannot read property 'length' of undefined
... Datatable gets stuck saying "Loading ..."
I'm sure this is possible due to my data formatting JSON
. Can anyone point me in the right direction?
source to share
You have to access the object Log
in data
, because it is an array that column
will scroll as you build your table. The plugin works by assuming your array name is called data
, that is:
{
"data": [
// Array of objects
]
}
But since you are using Log
in your case:
{
"Logs": [
// Array of objects
]
}
... you will need to manually specify the attribute dataSrc
(because you are using a custom data property ):
$(document).ready(function() {
$('#example').dataTable( {
"ajax": {
"url": "/live/log",
"dataSrc": "Logs"
},
"columns": [
{"data": "date"},
{"data": "eventType"},
{"data": "str"}
]
});
});
source to share