DataTables from Ajax source order-by data-order and display formatted date

Nicekiwi picture Nicekiwi · Dec 4, 2015 · Viewed 13.3k times · Source

Basically I want to pull data from ajax into my columns, but I want the cells in the columns to have the data-order attribute on them with the value from the ajax call and use moment.js to format the data in the cell.

I'm assuming this is the best way to make it pretty AND orderable. I found the plugin for datetime-momentJS, but it will only order the date, not format it as well.

var dataTable = $('#products').DataTable( {
  'processing': true,
  'ajax': '/products',
  'columns': [
    {
      'data': 'updated_at',
      'className':'date'
    }
  ]
});

right now I have this as the final result:

<td class="date">2015-11-08T11:00:00.000Z</td>

but the result I want is:

<td class="date" data-order="2015-11-08T11:00:00.000Z">11/08/2015</td>

Can I use the render option to do this somehow?

The moment code to format it like I want would be moment('2015-11-08T11:00:00.000Z').format('DD/MM/YY').

Answer

Bogdan picture Bogdan · Oct 27, 2016

You can achieve the same result directly by sending orthogonal data through Ajax.

The timestamp formatting you will be doing on server side and you won't need any other JavaScript callbacks and plugins.

Code sample form the link above

JavaScript:

$(document).ready(function() {
    $('#example').DataTable( {
        ajax: "data/orthogonal.txt",
        columns: [
            { data: "name" },
            { data: "position" },
            { data: "office" },
            { data: "extn" },
            { data: {
                _:    "start_date.display",
                sort: "start_date.timestamp"
            } },
            { data: "salary" }
        ]
    } );
} );

Ajax:

{
  "data": [
    {
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": {
        "display": "Mon 25th Apr 11",
        "timestamp": "1303686000"
      },
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
    ...
    }
}