Dynamically set column data from ajax source

Dynamically set column data from ajax source

rocheroche Posts: 4Questions: 1Answers: 0

Hi, I'd like to know if it is possible to set the column.data from one of the object returned by datatable ajax?

ie.
My JSON:

{ 
"column ": [ {"data" : "code"}, {"data" : "title"} ],
"data" : [{"code" : "AAA", "title" : "TripleA"}, {"code" : "W", "title" : "DoubleU"}]
}

datatable options

"ajax": "url/to/json"
"columns" : column

I have a function that initialize a bunch of table at once with mostly same setting (beside ajax url and of course, the column and data itself). And when I do that, it throws error "column is not defined", even though the XHR request returned by datatable shows that whole JSON is returned (column and data).

Thanks in advance.

Replies

  • AliBahAliBah Posts: 11Questions: 0Answers: 0

    You need to post full example, html + table initialization. Otherwise it's hard to understand where exactly you made an error.

  • rocheroche Posts: 4Questions: 1Answers: 0
    edited September 2015

    Thanks for replying. Here is my function

    $('.datatable').each(function(){
       //this return the url to get the data source, might be different for each table
       var url = $(this).attr('data-url'); 
    
       $(this).DataTable({
            "ajax" : url,
            "columns" : column
       });
    });
    

    And my JSON returned from the server is:

    {
    //this is the column source -- to be used in column init
    "column ": [ {"data" : "code"}, {"data" : "title"} ],
    //this is the data source -- to output to the table
    "data" : [{"code" : "AAA", "title" : "TripleA"}, {"code" : "W", "title" : "DoubleU"}]
    }
    

    HTML:

    <table class="datatable" data-url="some/url/to/data/source">
    <thead><tr><td>Code</td><td>Title</td></tr></thead>
    <tbody></tbody>
    </table>
    

    Everything is ok (it will output the data) if I manually write the column like:

    ...
    "columns" : [{"data" : "code"}, {"data" : "title"}]
    ...
    

    but if I refer to the "column" key instead, it will return (in console) : "column" is not defined. (Also, no data is shown in the table)

    It is as if datatable only 'get' the "data" part of the JSON returned, not the whole JSON, which is why I can set the "columns" manually using any key under "data", but not with "column" (because key "column" is sibling to key "data").

  • pthomas931pthomas931 Posts: 1Questions: 0Answers: 0

    Sadly, the only method I've found to do this requires two server calls (one for columns, one for data). Like this:

    $.get("/getColumns", function (cols) { $("#table").DataTable({columns: cols}); } );

    Allan answers this here: http://www.datatables.net/forums/discussion/3519/getting-column-names-from-ajax-source

This discussion has been closed.