How to parse JSON received from Datatables ajax call? How to parse JSON received from Datatables ajax call? json json

How to parse JSON received from Datatables ajax call?


Something like this:

$('#transactions').dataTable({    "ajax" : {        "url" : "/transactions",        "dataSrc" : function (json) {            // manipulate your data (json)            ...            // return the data that DataTables is to use to draw the table            return json.data;        }    }});

Docs: https://datatables.net/reference/option/ajax.dataSrc


Don't use the url feature of DataTable, make the Ajax call yourself

$.getJSON('/transactions', function(response) {  $('#transactions').dataTable({    processing: true,    data: response.data,    columns: [      { data: "car"},      { data: "card_number"},      { data: "invoice"},      { data: "status"}    ]  });  window.someGlobalOrWhatever = response.balance});


Since DataTables 1.10, you may use the ajax.json() function: https://datatables.net/reference/api/ajax.json()I have implemented it in the example code below.

$( document ).ready(function() {  $('#search-form').submit(function(e) {    e.preventDefault();    var table = $('#location-table').DataTable({      destroy: true,      ajax: "/locations.json",      columns: [        { "data": "code" },        { "data": "status" },        { "data": "name" },        { "data": "region" },        { "data": "address" },        { "data": "city" },        { "data": "state" },        { "data": "zip" },        { "data": "phone_number" },      ]    })  table.on( 'xhr', function () {    var json = table.ajax.json();    $('#totals').text(json.totals)  });  })});

NOTE for this to work you must initialize the datatable with $('#location-table').DataTable() and not $('#location-table').dataTable (the difference being the capitalized D)