Create columns from data pulled from ajax.json()
Create columns from data pulled from ajax.json()
Is there a way to create the columns for the table via content pulled from ajax.json()
?
I have a table thats 100% dynamic, right now to construct the columns, I render the table with just the thead
and tfoot
, the thead
has a bunch of data-field
with the column names as the values.
Heres the related JS that creates the columns for the columns
:
var columns = [];
// Add the columns from the fields in the table
$('#data-table').find('thead').eq(0).find('tr').find('th')
.each(function( i, col ){
columns.push({
data : $( this ).data( 'field' ),
name : $( this ).data( 'field' ),
visible : $( this ).data( 'visible' ) != false
});
});
Example
If the PHP renders this:
<table id="data-table" class="table width-full display compact table-condensed" >
<thead id="main-header">
<tr>
<th data-field="creator" data-visible="true" class="field-creator">Creator</th>
<th data-field="modifier" data-visible="true" class="field-modifier">Modifier</th>
<th data-field="status" data-visible="false" class="field-status">Status</th>
</tr>
</thead>
<tfoot>
<tr>
<th data-field="creator" data-visible="true" class="field-creator">Creator</th>
<th data-field="modifier" data-visible="true" class="field-modifier">Modifier</th>
<th data-field="status" data-visible="false" class="field-status">Status</th>
</tr>
</tfoot>
</table>
Then what would be handled to DT via columns
would be:
[
{
data: 'creator',
name: 'creator',
visible: true
},
{
data: 'modifier',
name: 'modifier',
visible: true
},
{
data: 'status',
name: 'status',
visible: false
}
]
So basically, all that same data is in the AJAX source thats pulled via ajax
, and all visible via ajax.json()
, I use the dataSrc
to pull all the actual table rows from an array within a larger data set, which contains everything id need for the table.
I know that the columns
doesnt take a closure as a value, so I cant do much there. But is there another way?
This question has an accepted answers - jump to answer
Answers
P.S. I realize I could do an AJAX call to the same data source prior to initializing DT, but id really like to handle as much of it as I can within the DT API
Bump? :-) i havent found a way for this yet, hoping someone knows a way
Unfortunately no. DataTables does not implement dynamic columns at this time, so columns cannot be added and removed from the table after initialisation. They must be set before the DataTable is created.
What you can do, if you want to define your columns from an Ajax request is make your own Ajax request:
With the next major update to DataTables I do plan to add the ability to have this specified by the server in the initial Ajax request - it still won't be fully dynamic columns, but it will at least allow the server some control.
The biggest downside is that JSON cannot contain functions, so the full range of options for the column definitions cannot be defined using this method.
Allan