1

I am trying to get data into DataTables from AJAX source as below:

$('#DT').DataTable( {
    "paging": false,
    "processing": true,
    "info": false,
    "ajax": 'http://localhost:5000/get_data'
} );

It's working when the server provides data in this format as below:

{
  "data": [
    [
      1,
      "0FL0BW1MA",
      "2018-03-24 15:00",
      "Lisbon ,Lisboa ,Portugal",
      "CMA CGM GEORG FORSTER",
      "ADALV",
      "2018-05-08 02:00",
      "ADENC"
    ]
  ]
}

But the actual server sends response in JSON key:value format as follows:

{
  "data": [
    {
      "containers": 4, 
      "destination_port": "2018-05-08 02:00", 
      "eta": "CMA CGM GEORG FORSTER", 
      "etd": "2018-03-24 15:00", 
      "loading_port": "Lisbon ,Lisboa ,Portugal", 
      "vessels": "0FL0BW1MA"
    }    
  ]
}

So, My question is how can I load the actual JSON data to data table?

2
  • @RoryMcCrossan Actually, It would be great if I could use the existing API. Otherwise, I should ask. Commented Jul 12, 2018 at 16:27
  • That's what I assumed. Hopefully the answer I added below helped. Commented Jul 12, 2018 at 16:28

2 Answers 2

3

You didn't provide the content of the #DT table. But my guess is that you already populated it with TH's?

if that is the case you should be able to do something like this

// This is the data you get from the server
var strData = {
  "data": [
      {
      "containers": 4, 
      "destination_port": "2018-05-08 02:00", 
      "eta": "CMA CGM GEORG FORSTER", 
      "etd": "2018-03-24 15:00", 
      "loading_port": "Lisbon ,Lisboa ,Portugal", 
      "vessels": "0FL0BW1MA"
      }    
  ]
}

// Creating the new array according to your specifications
var arrData = [];
for (var key in strData.data) {
    if (!strData.data.hasOwnProperty(key)) continue;

    var obj = strData.data[key];
    var tmpArr = []
    for (var prop in obj) {
        if(!obj.hasOwnProperty(prop)) continue;
        tmpArr.push(obj[prop]); 
    }
    arrData.push(tmpArr);
}

$(document).ready( function () {
    $('#table_id').dataTable( {
        "data": arrData,
    } );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

<table id="table_id" class="display">
        <thead>
            <tr>
                <th>
                    containers
                </th>
                <th>
                    destination_port
                </th>
                <th>
                    eta
                </th>
                <th>
                    etd
                </th>
                <th>
                    loading_port
                </th>
                <th>
                    vessels
                </th>
            </tr>
        </thead>
</table>

You can however provide datatables with an array of the columns instead of defining them in html, which i would probably do. I think it would make things more dynamic.

--- Updated code when using the ajax function in DataTables

First we need to make a function for converting the json

function convertArray(json) {
    var arrData = [];
    for (var key in json.data) {
        if (!json.data.hasOwnProperty(key)) continue;

        var obj = json.data[key];
        var tmpArr = []
        for (var prop in obj) {
            if(!obj.hasOwnProperty(prop)) continue;
            tmpArr.push(obj[prop]); 
        }
        arrData.push(tmpArr);
    }
    return arrData;
}

I have never used DataTables before but their documentation states that one can use dataSrc to pass in a custom function. Lets try using it like so

$('#DT').DataTable( {
    "paging": false,
    "processing": true,
    "info": false,
    "ajax": {
        "url": "http://localhost:5000/get_data",
        "dataSrc": function ( json ) {
            return convertArray(json);
        }
    }
} );

This should pass the json response to our function and convert the data.

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

2 Comments

I tried this one. I am getting an empty array in the result. What might be the issue?
In order to use the script we will have to make it into a function, so that we can pass data from the ajax response and get the result you need. I edited the post with a new function and the changes you need to make to your existing script in order to make it work. - fingers crossed :)
1

Assuming it's not possible for you to amend the response coming from the server, which would be the best solution by far, then you can amend the response from an array of objects to a nested array by using map(), like this:

var source = {
  "data": [{
    "containers": 4,
    "destination_port": "2018-05-08 02:00",
    "eta": "CMA CGM GEORG FORSTER",
    "etd": "2018-03-24 15:00",
    "loading_port": "Lisbon ,Lisboa ,Portugal",
    "vessels": "0FL0BW1MA"
  }]
};

var output = {
  data: source .data.map(function(item) {
    return [
      item.containers,
      item.vessels,
      item.etd,
      item.loading_port,
      item.eta,
      'ADALV', // not clear where this value is in the source 
      item.destination_port,
      'ADENC' // not clear where this value is in the source 
    ]
  })
}

console.log(output);

2 Comments

This could be good. It would be great if you give any idea to load the mapped data to DataTables. Please see the first portion of code at my question.
You can use $.ajax to retrieve the data from your API, put it through the logic above then apply it to the DataTable by using the data property: datatables.net/examples/data_sources/js_array.html

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.