I'm trying to upgrade my system to use 1.10 instead of 1.9 of DataTables and I'm trying to find a way to pass back the row contents using a JSON object instead of a list. Specifically instead of passing back data in the format [['data','data','data'],['data','data','data'],etc..]
I want to put it in the format [['colA':'data','colB':'data','colC':'data']]
.
Right now I've got my AJAX function returning the data in that format and I'm trying to initialize with this code:
$("table").DataTable({
"columnDefs": [
{"name": "wo_status", "title": "wo_status", "targets": 0},
//repeat for each of my 20 or so fields
],
"serverSide": true,
"ajax": "url/to/ajax/function"
});
The results are coming back from my AJAX function correctly but DataTables is trying to find an index of 0 in row 0 and failing to find it because my table cells are indexed by their column name instead of a numerical index. Does anyone know how to tell DataTables to use the column names specified in columnDefs
(or in some other option I haven't found) instead of numerical indices?
Use columns.data
option to specify property names as shown below:
$("table").DataTable({
"columns": [
{ "data": "colA", "name": "colA", "title": "colA" },
{ "data": "colB", "name": "colB", "title": "colB" },
{ "data": "colC", "name": "colC", "title": "colC" }
//repeat for each of my 20 or so fields
],
"serverSide": true,
"ajax": "url/to/ajax/function"
});
Use forEach in fnServerParams function...
$("table").DataTable({
"columns": [{
"data": "colA"
}, {
"data": "colB"
}, {
"data": "colC"
}],
"serverSide": true,
"ajax": "url/to/ajax/function",
fnServerParams: function(data) {
data['order'].forEach(function(items, index) {
data['order'][index]['column'] = data['columns'][items.column]['data'];
});
},
});
Thanks @ahmeti I've updated your approach :)
ajax: {
url: fetchUrl,
data: function ( data ) {
data['columns_map'] = {};
data['columns'].forEach(function(item, index) {
data['columns_map'][item.data] = data['columns'][index];
});
data['order'].forEach(function(item, index) {
data['order'][index]['column'] = data['columns'][item.column]['data'];
});
return {"data": JSON.stringify(data)};
}
},
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