Datatables - dynamic columns

10,643

Solution 1

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)

Solution 2

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!!

Share:
10,643
Ioannis Kokkinis
Author by

Ioannis Kokkinis

By Day : Work, work work By Night : Fun, fun, fun

Updated on June 08, 2022

Comments

  • Ioannis Kokkinis
    Ioannis Kokkinis almost 2 years

    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",
    .......
    
  • Ioannis Kokkinis
    Ioannis Kokkinis about 8 years
    So when I need to update the source of the datatable I am running : var table = $('#datatable-buttons').DataTable(); var ajaxurl = table.ajax.url(); So this way I just update the ajaxurl variable. In your method above, what would I need to call for the update in columns and data to happen?
  • Ioannis Kokkinis
    Ioannis Kokkinis about 8 years
    Do you think I could stick this somehwere when I get the json for the databale? for example add a "complete" = function.... on the datatable ajax call?
  • oscilatingcretin
    oscilatingcretin about 7 years
    Is there a way to set the columns after the call for data, but before it loads the data into the grid? I will never know the columns at any point in time, so I will need to set the columns based on the JSON that is returned.