Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using column names with DataTables with AJAX data source

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?

like image 302
Jesse Green Avatar asked Aug 20 '15 17:08

Jesse Green


3 Answers

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"
});
like image 105
Gyrocode.com Avatar answered Oct 08 '22 06:10

Gyrocode.com


Use forEach in fnServerParams function...

enter image description here

$("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'];
    });
  },
});
like image 29
ahmeti Avatar answered Oct 08 '22 08:10

ahmeti


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)};
        }
    },
like image 37
madzohan Avatar answered Oct 08 '22 08:10

madzohan