Smern
Smern

Reputation: 19086

Populate Datatable from ajax json

My table is not populating. I can see that it is getting the correct JSON

JSON Data received looks like this:

[
  {
    "id": "1",
    "name": "FooBar",
    "predicted": "0",
    "points": "1",
    "section_id": "1",
    "detail_alias": ""
    ...
  },
  ...
]

HTML

<table id="example"></table>

JS

$('#example').dataTable( {
    "ajaxSource": "rest/index.php?m=foo",
    "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "detail_alias" },
        { "data": "points" }
    ]
} );

All I'm seeing in my browser is:

enter image description here

It says "Loading..." when the network tab shows that the call had a 200 response with the correct data.

Why isn't the table populating?

Upvotes: 11

Views: 77281

Answers (7)

Daniela Solis
Daniela Solis

Reputation: 11

I had the same problem while using Codeigniter json_encode type of data, it returned a Flat array data source after a few days of trying

"aaData": data,

I finally got it working using

"ajax": { "url": "index.php/controller/function", "dataSrc": "" },

Instead of

"data": [ [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],

But in reality, it's quite simple see data table Ajax documentation

$(document).ready(function() {
    $('#t1').DataTable( {
        "ajax": {
            "url": "<?php echo base_url(); ?>index.php/controller/function",
            "dataSrc": ""
        },
        "columns": [
            { "data": "CCODIGOCLIENTE" },
            { "data": "CRAZONSOCIAL" },
            { "data": "PENDIENTE" },
            { "data": "siete" },
            { "data": "sietev" },
            { "data": "catorcev" },
            { "data": "catorce" },
            { "data": "veintiunov" },
            { "data": "veintiuno" },
            { "data": "mes" },
            { "data": "bimestre" },
            { "data": "trimestre" }
        ]
    } );
} );
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

        <table id="t1" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>QTime</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

A few pointers for beginners...

  1. Ensure that your script is positioned below your libraries.
  2. Verify that the number of columns matches your data.
  3. Ensure that your data table ID is unique.

Good luck to you all.

Upvotes: 1

Ashok Parmar
Ashok Parmar

Reputation: 408

Followup the below style. It's work

[{"first_name": "Ashok","last_name": "Parmar"}]

$('#dataTbl').DataTable({

        ajax:{
           url:  '/view',
           type: 'POST',
           
           contentType: 'application/json',
           success: function(data){
                
                populateDataTable(data);
           },
           error: function (e) {
                console.log("There was an error with your request...");
                console.log("error: " + JSON.stringify(e));
           }
        }//ajax

      }); // table

function populateDataTable(data) {
        $("#dataTbl").DataTable().clear();
        var row = 1;
        $.each(data, function (index, value) {
            $('#dataTbl').dataTable().fnAddData( [
                row,
                value.first_name,
                value.last_name 
              ]);

           row++;
        });
    }

Upvotes: 3

Hannah Benhamou
Hannah Benhamou

Reputation: 11

var $table = $('#productListTable');

// execute the below code only where we have this table
if($table.length) {
    //console.log('Inside the table!');

    var jsonUrl = '';
    if(window.categoryId == '') {
        jsonUrl = window.contextRoot + '/json/data/all/products';
    }
    else {
        jsonUrl = window.contextRoot + '/json/data/category/'+ window.categoryId +'/products';
    }



    $table.DataTable( {

        lengthMenu: [[3,5,10,-1], ['3 Records', '5 Records', '10 Records', 'ALL']],
        pageLength: 5,
        ajax: {
            url: jsonUrl,
            dataSrc: ''
        },
        columns: [
                  {
                      data: 'code',
                      bSortable: false,
                      mRender: function(data, type, row) {

                          return '<img src="'+window.contextRoot+'/resources/images/'+data+'.jpg" class="dataTableImg"/>';

                      }
                  },
                  {
                      data: 'name'                        
                  },
                  {
                      data: 'brand'                       
                  },
                  {
                      data: 'unitPrice',
                      mRender: function(data, type, row) {
                          return '&#8377; ' + data
                      }
                  },
                  {
                      data: 'quantity',
                      mRender: function(data, type, row) {

                          if(data < 1) {
                              return '<span style="color:red">Out of Stock!</span>';
                          }

                          return data;

                      }
                  },

Upvotes: 0

shamimiceewu025
shamimiceewu025

Reputation: 881

Js Code Where json url : getjsonrequest.php

`

$(document).ready(function() {
    $('#tableid').DataTable( {
        "ajax": {
            "url": "getjsonrequest.php",
            "dataSrc": ""
        },
        "columns": [
            { "data": "INDEX1" },
            { "data": "INDEX2" }
        ]
    } );
} );

`

Html Code

`

<table id="tableid" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Index 1</th>
                <th>Index 2</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Index 1</th>
                <th>Index 2</th>
            </tr>
        </tfoot>
    </table>

`

Upvotes: 0

Smern
Smern

Reputation: 19086

So the ajaxSource in my question was expecting data to be formatted as such:

{ data: [ { ...

And I didn't want to have to modify my back end to send data in this format as it would cause problems in other places. I'm assuming other people that end up on this page looking for a solution will likely have the same issue.

My solution was to get the data via jQuery.ajax() and then pass it in to the aaData field, like this:

$.ajax({
    'url': "/rest/index.php?m=foo",
    'method': "GET",
    'contentType': 'application/json'
}).done( function(data) {
    $('#example').dataTable( {
        "aaData": data,
        "columns": [
            { "data": "id" },
            { "data": "name" },
            { "data": "detail_alias" },
            { "data": "points" }
        ]
    })
})

This allows me to not have to worry about changing the json data from the format in the question.

I like this way better anyway as I feel it gives me more flexibility if I wanted to do modify or use the data for anything else at the same time.

Upvotes: 25

Poldo
Poldo

Reputation: 1932

I think you must return your json with the array of "aaData"

return dataTabledata['aaData'] = 'your json data'

By default DataTables will use the "aaData" property of the returned data which is an array of arrays with one entry for each column in the table.

In your jQuery create ajax that will handle the data from your server side

 function getdtData(){
    /*clear table row first*/
    $('#sample').dataTable().fnDestroy();
    /*populate your datatable using ajax*/
    $('#sample').dataTable({
    "sDom": 'frtip',
    "bServerSide": true,
     /*server side source*/
    "sAjaxSource": "rest/index.php?m=foo",
     /* we use sDom to specify the lenght of the pagination if you will using pagination in your data table*/
    "lengthMenu": [[ 5, 5], [ 5, 5]],
    "aoColumnDefs": [
        { "aTargets": [ 0 ], "bSortable": false},
        { "aTargets": [ 1 ], "bSortable": false },
        { "aTargets": [ 2 ], "bSortable": false },
        { "aTargets": [ 3 ], "bSortable": false }
    ]
});

refer to this documentation http://legacy.datatables.net/usage/server-side

Upvotes: 1

nyedidikeke
nyedidikeke

Reputation: 7658

The table is not populating because you have no data object in your received JSON data but referencing it (data object) for display in the table columns.

Based on your dataTable initialisation, your JSON data should look like this:

{"data":[
  {
    "id": "1",
    "name": "FooBar",
    "predicted": "0",
    "points": "1",
    "section_id": "1",
    "detail_alias": ""
    ...
  },
  ...
]}

Upvotes: 0

Related Questions