Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables - dynamic columns

I understand that this question has been asked before, but my variation does not match the other answers.

I have a json data source in this form :

    {
      "columns":[
          {"title":"Store Number","data":"StoreNbr"},
          {"title":"Store Name","data":"StoreName"},
          {"title":"2016-01-01","data":"2016-01-01"},
          {"title":"2016-01-02","data":"2016-01-02"}
      ],
      "data":[
          {"2016-01-01":"51","StoreNbr":"1","StoreName":"Store 1","2016-01-02":"52"}
      ]
  }

I am loading the data like this :

$("#datatable").DataTable({
            "ajax": {
            "url": "http://myjsonurl-that-produces-above-response",
           "dataSrc": "data"
        },

    "columns": [
       {"title":"Store Number","data":"StoreNbr"},
       {"title":"Store Name","data":"StoreName"},
       {"title":"2016-01-01","data":"2016-01-01"},
       {"title":"2016-01-02","data":"2016-01-02"},
     ],   
     dom: "Bfrtip",
    "bProcessing": true,
    "bServerSide" : true
});

The above works flawlessly. What I need, is to load the columns dynamically, like this :

"columns": $.getJSON($('#datatable').DataTable().ajax.url(), 
           function(json){
              return (JSON.stringify(json.columns));  
           });

All I get is a aDataSource error. If I run the .getJSON thing anywhere else in the code I get the expected response, the one I need. Any ideas?

I would like to make this to work as it is preferably as my datasource keeps changing based on filters I apply that affect the json source, dataset etc.

Update :

The way the table is initialized :

<script type="text/javascript"> 
          TableManageButtons.init();

TableManageButtons = function () {"use strict"; return { init: function () { handleDataTableButtons()  } }}();

var handleDataTableButtons = function () {
    "use strict";
    0 !== $("#datatable-buttons").length && $("#datatable-buttons").DataTable({
            "ajax": {
            "url": "http://myjsonurl.php",
.......
like image 328
Ioannis Kokkinis Avatar asked Apr 29 '26 16:04

Ioannis Kokkinis


2 Answers

Try to get the columns first and then proceed with datatables initialization:

$.getJSON('url/for/colums', function(columnsData) {
   $("#datatable").DataTable({
      ...
      "columns": columnsData
   });
});

EDIT

If I understand correctly, you want to do this:

$("#datatable").DataTable({
       "ajax": {
       "url": "http://myjsonurl-that-produces-above-response",
       "dataSrc": "data"
    },
    "columns": getColumns(), //Execute $.getJSON --> asynchronous (the code continous executing without the columns result)
    dom: "Bfrtip",
    "bProcessing": true,
    "bServerSide" : true
});

In this way, when you call getColumns() the execution is asynchronous, so the columns are going to be undefined.

That's why you have to call the DataTable initializer in the getJSON callback function.

Another way might be to get the columns in a not asynchronous function setting async: false (Check this question)

like image 181
kapantzak Avatar answered May 01 '26 06:05

kapantzak


You can form a custom js function to put your headers in place once you get the response from server. Have a look into below code:

JSON response from server:

{
    "columns": [
        [ "Name" ],
        [ "Position" ],
        [ "Office" ],
        [ "Extn." ],
        [ "Start date" ],
        [ "Salary" ]
    ],
    "data": [
    [
      "Tiger Nixon",
      "System Architect",
      "Edinburgh",
      "5421",
      "2011/04/25",
      "$320,800"
    ],....
}

And js method to process it to put headers on place:

$( document ).ready( function( $ ) {
        $.ajax({
                "url": 'arrays_short.txt',
                "success": function(json) {
                    var tableHeaders;
                    $.each(json.columns, function(i, val){
                        tableHeaders += "<th>" + val + "</th>";
                    });

                    $("#tableDiv").empty();
                    $("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
                    //$("#tableDiv").find("table thead tr").append(tableHeaders);  

                    $('#displayTable').dataTable(json);
                },
                "dataType": "json"
            });
    });

Check this url for more clarification. Hope this helps!!

like image 39
Shri Avatar answered May 01 '26 06:05

Shri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!