jqueryajaxdatatables

Populate Datatable from ajax json


My table is not populating. I can see that it is getting the correct JSON

JSON Data received looks like this:

[
  {
    "id": "1",
    "name": "FooBar",
    "predicted": "0",
    "points": "1",
    "section_id": "1",
    "detail_alias": ""
    ...
  },
  ...
]

HTML

<table id="example"></table>

JS

$('#example').dataTable( {
    "ajaxSource": "rest/index.php?m=foo",
    "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "detail_alias" },
        { "data": "points" }
    ]
} );

All I'm seeing in my browser is:

enter image description here

It says "Loading..." when the network tab shows that the call had a 200 response with the correct data.

Why isn't the table populating?


Solution

  • So the ajaxSource in my question was expecting data to be formatted as such:

    { data: [ { ...

    And I didn't want to have to modify my back end to send data in this format as it would cause problems in other places. I'm assuming other people that end up on this page looking for a solution will likely have the same issue.

    My solution was to get the data via jQuery.ajax() and then pass it in to the aaData field, like this:

    $.ajax({
        'url': "/rest/index.php?m=foo",
        'method': "GET",
        'contentType': 'application/json'
    }).done( function(data) {
        $('#example').dataTable( {
            "aaData": data,
            "columns": [
                { "data": "id" },
                { "data": "name" },
                { "data": "detail_alias" },
                { "data": "points" }
            ]
        })
    })
    

    This allows me to not have to worry about changing the json data from the format in the question.

    I like this way better anyway as I feel it gives me more flexibility if I wanted to do modify or use the data for anything else at the same time.