Dovi Dovi - 18 days ago 9
JSON Question

DataTables ajax on nested data

I am using DataTables ajax to fill a table. I was following this example and it works if my json looks like their example, however my 'data' is a nested object in my json and then it is not able to fill the table because fails in getting the values from the json.

This json works:

{
"data": [
{"id": "myid1", "name": "name1"},
{"id": "myid2", "name": "name2"}
]
}


But my json looks like this, and it does not work

{
"result": {
"data": [
{"id": "myid1", "name": "name1"},
{"id": "myid2", "name": "name2"}
]
}
}


That's my html (which works with the first json):

<table id="myTable" class="tabletable-bordered dataTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
</tr>
</thead>
<tbody>
<td></td>
<td></td>
</tbody>
</table>


And that's my js:

$('#myTable').DataTable( {
"ajax": "/names",
"processing": true,
"dataSrc" : "result.data",
"columns": [
{ "data": "name" },
{ "data": "id" }
]
} );


As you can see I try to access to my nested
data
by setting
dataSrc
to
result.data
, but nothing is shown in the table.

I cannot change the format of the json response, do you know if then is not possible to use DataTables ajax with this json? Thanks!

Answer

I had more complex processing requirements so I implemented my own ajax function but I think you can get away with this:

$('#myTable').DataTable( {
  "processing": true,
  "ajax": {
    "url": "/names",
    "dataSrc" : function(jsonObj) {
        // Just being safe here
        if(!jsonObj.results || !json.results.data) {
          return [];
        }

        return jsonObj.results.data;      
    }
  },
  "columns": [
    { "data": "name" },
    { "data": "id" }
  ]
});

Here is the reference for this: https://datatables.net/reference/option/ajax