3

I am using DataTables with Jquery, I have an JSON object data source I want to fetch via Ajax and display in the table.

JSON data is returned from the /live/log url and is formatted as follows :

{
    "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 Table HTML :

<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 to fetch and populate the datatable :

$(document).ready(function() {
  $('#example').dataTable( {
    "ajax": "/live/log",
    "columns": [
        {"data": "date"},
        {"data": "eventType"},
        {"data": "str"}
      ]

  });
});

I can see via the debugger the JSON data is being fetched correctly.

I seem to get an error in the datatables js relating to the JSON data.

Value aData in fnInitalise is null - Uncaught TypeError: Cannot read property 'length' of undefined. The Datatable gets stuck saying "Loading..."

I'm sure it's probably due to my JSON data formatting. Can anyone point me in the right direction?

3
  • Have a go with the following JS a let me know: pastebin.com/zMcaayV8. Commented Apr 22, 2015 at 15:13
  • Hi Muggles, Thanks, just tried the suggestion, no change same error :( Commented Apr 22, 2015 at 15:18
  • Maybe you need array json not object with one key. Commented Apr 22, 2015 at 15:28

1 Answer 1

5

You should access the Log object in data, because it is the array that the column will loop through when constructing your table. The plugin works by assuming that the name of your array is called data, i.e.:

{
    "data": [
        // Array of objects
    ]
}

But since you are using Log in your case:

{
    "Logs": [
        // Array of objects
    ]
}

...you will need to manually specify the dataSrc attribute (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"}
      ]

  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.