SaeX
SaeX

Reputation: 18691

Populating JSON objects in DataTables

I'm using DataTables 1.10.x and would like to populate the data in my table using JSON objects.

$(document).ready( function () {
    $('#diagtable').dataTable( {
        "ajax": '/api/v1/diag/1/',
        "columns": [
            { "date": "date" },
            { "diagnosis": "diagnosis" }
        ],
        dom: 'T<"clear">lfrtip',
    } );
} );

I realize the { "date": "date" }, does not look right, but I'm unsure what else to use in between the first quotes.

My table goes below:

<table id="diagtable" class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>Date</th>
      <th>Diagnosis</th>
      <th>&nbsp;</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

My AJAX call returns the following JSON:

[
    {
        "date":"2010-03-20",
        "diagnosis":"Test1"
    },
    {
        "date":"2015-03-21",
        "diagnosis":"Test2"
    }
]

I see the proper AJAX call is made by DataTables (HTTP 200), but the table says "loading...".

I tried playing around with the below, but still no data gets populated in my table.

"aoColumns": [
   { "mData": "date" },
   { "mData": "diagnosis" }
]

The documentation shows to use:

    "columns": [
        { "data": "name" },
        ...

But I don't have this "data" or similar in my JSON. I cannot change my JSONs either.

Any idea what I'm doing wrong?

Upvotes: 1

Views: 1615

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58870

Your returned data in JSON format differs from the default format expected by DataTables 1.10.x, see ajax.dataSrc or Ajax data source (objects) example.

Since you mentioned that you cannot change your JSON structure, the solution is to alter dataSrc property, see below

$(document).ready( function () {
    $('#diagtable').dataTable( {
        "ajax": {
            "url": '/api/v1/diag/1/',
            // Get JSON data from a plain array 
            // rather than an array in an object
            "dataSrc": ""
        },
        "columns": [
            { "data": "date" },
            { "data": "diagnosis" }
        ],
        dom: 'T<"clear">lfrtip',
    } );
} );

Upvotes: 1

Related Questions