Reham Fahmy
Reham Fahmy

Reputation: 1128

Getting data from JSON array in a table

If a website gives json array data as follow

mycallback([{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}])

How i call this json array data into a table

My try but didn't worked!

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('#example').dataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "http://WebSite_URL.com/data.php",
            "dataType": "jsonp",
            "jsonp":"mycallback"

        }
    } );
} );
</script>

<table id="example" cellspacing="0" width="100%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</table>

Upvotes: 0

Views: 79

Answers (2)

fijas
fijas

Reputation: 1274

By default DataTables expects the data source to be contained within a variable named data like so:

{data:[{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}]}

But, in your case, I am assuming that changing the json format is not an option as it is a Jsonp request. So, I am assuming that your data is formatted as a "flat" array and can't be changed like this:

[{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}]

Now, dataTables allow "flat" array structures to be used by giving the dataSrc option within the ajax array as a blank value. Also since your data source has a key for each value, you have to specify that using the columns option. So, your datatables code would become:

$('#example').dataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "http://WebSite_URL.com/data.php",
        "dataType": "jsonp",
        "jsonp":"mycallback",
        "dataSrc": ""
    },
    "columns": [
        {"data": "id"},
        {"data": "name"},
        {"data": "age"},
    ]
} );

This is of course assuming that your ajax call and jsonp callback are all done properly.

Upvotes: 1

Tanmoy Majumdar
Tanmoy Majumdar

Reputation: 458

This is a JSONP call and you provide a function name(here "mycallback").So, the server will send data such that it is calling your provided function with the JSON data.Here,mycallback([{"id":"2","name":"Kelly","age":"12{"id":"3","name":"Robby","age":"12"}]).

What you have to do is defining a function with name "mycallback" which will have a parameter and you can do whatever you want there.

Example:

  function mycallback(data){
                var table = document.getElementById('example');
                var tableHtml = '' // make the html here with this data (using a template engine)
                table.innerHTML = tableHtml;
          }

Upvotes: 1

Related Questions