Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable with JSON data

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.

like image 342
Onextrapixel Avatar asked Jun 25 '18 12:06

Onextrapixel


1 Answers

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

like image 83
Preston Avatar answered Sep 25 '22 21:09

Preston