In jquery Datatables is it possible to define columns with a server-side script? I need something like this
The columns with dates have to be loaded from server. Then number of columns can vary.
I think I have found what you were looking for
I will paste some code + post a link to a similar Q' in which you will get much more info...
$.ajax( {
"url": 'whatever.php',
"success": function ( json ) {
json.bDestroy = true;
$('#example').dataTable( json );
},
"dataType": "json"
} );
where json is something like this
{
"aaData": [
[ "2010-07-27 10:43:08", "..."], [ "2010-06-28 17:54:33", "..."],
[ "2010-06-28 16:09:06", "..."], [ "2010-06-09 19:15:00", "..."]
] ,
"aaSorting": [
[ 1, "desc" ]
],
"aoColumns": [
{ "sTitle": "Title1" },
{ "sTitle": "Title2" }
]
}
here a link to the original thread
Column definition via JSON array (ajax)
To expand on what Kamal Deep Singh was saying:
You could dynamically create the table on the fly, then apply datatables to it to get datatables' functionality.
// up in the html
<table id="myDatatable" class="... whatever you need..."></table>
and then:
// in the javascript, where you would ordinarily initialize the datatable
var newTable = '<thead><tr>'; // start building a new table contents
// then call the data using .ajax()
$.ajax( {
url: "http://my.data.source.com",
data: {}, // data, if any, to send to server
success: function(data) {
// below use the first row to grab all the column names and set them in <th>s
$.each(data[0], function(key, value) {
newTable += "<th>" + key + "</th>";
});
newTable += "</tr></thead><tbody>";
// then load the data into the table
$.each(data, function(key, row) {
newTable += "<tr>";
$.each(row, function(key, fieldValue) {
newTable += "<td>" + fieldValue + "</td>";
});
newTable += "</tr>";
});
newTable += '<tbody>';
$('#myDatatable').html(newTable); // replace the guts of the datatable's table placeholder with the stuff we just created.
}
});
// Now that our table has been created, Datatables-ize it
$('#myDatatable').dataTable();
Note you can put settings in that .dataTable() as normal, however, not 'sAjaxSource' or any of the associated data-getting functions -- this is applying datatables to an already existing table, one we created on the fly.
Ok, so it's kind of a hacky way of doing it, but it should work.
There isn't currently a built in method of doing this with datatables dynamically. See here: https://github.com/DataTables/DataTables/issues/273
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With