Using column names with DataTables with AJAX data source
Solution 1
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"
});
Solution 2
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'];
});
},
});
Solution 3
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)};
}
},
Jesse Green
Updated on June 09, 2022Comments
-
Jesse Green almost 2 years
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? -
Admin over 5 yearsIs this setup required in order to use the table.ajax.reload(); Ajax reload does not seem to work with column_def
-
Ali about 5 yearsThank you. you have shown the path of secret treasure
-
Armitage2k over 4 yearswhy do you have to define
data
,name
andtitle
? Wouldntname
be enough? -
Gyrocode.com over 4 years@Armitage2k, you don't have to define
name
andtitle
, they were in the original question. Usuallydata
is enough.