DataTable with JSON data
Asked Answered
E

1

7

I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.

function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
  if ( request.readyState === 4 && request.status === 200 ) {
    var JSONObject = JSON.parse(request.responseText);
    createTable(JSONObject);
  } else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}

Requesting the JSON file via a XMLHttpRequest() request.

short sample of the JSON object:

{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
  "report-metadata": {
    "timestamp": 1528235303.721987,
    "from-ip": "0.0.0.0"
  }, 
//and so on...

Currently only trying to show the meta part in a DataTable table:

function createTable(jsonData){ 
 $(document).ready(function(){
  $('#table').dataTable({
    data: jsonData,
    columns: [
      { data: 'meta.type' },
      { data: 'meta.version' }
    ]
  });
 });
}

index.html part:

<table id="table" class="display" style="width:100%"></table>

Only getting a No data available in table when running, and I am obviously missing something.

Extensor answered 25/6, 2018 at 12:48 Comment(0)
M
12

The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.

var jsonData = [
    { "meta": { "version": 1, "type": "test" } }
];

$('#table').DataTable({
    "data": jsonData,
    "columns": [
      { "data": "meta.type" },
      { "data": "meta.version" }
    ]
});

https://datatables.net/reference/option/data

Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax

Melanochroi answered 25/6, 2018 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.