How to parse JSON received from ajax Datatables call?

I can successfully populate my datatable with an ajax call, but then I don’t know how to parse the JSON that is received with the datatable with this ajax call.

Here is my JavaScript code that makes an ajax call on the server and populates my data correctly:

$('#transactions').DataTable({ "processing": true, "ajax": { "url": "/transactions }, "columns": [ { "data": "car"}, { "data": "card_number"}, { "data": "invoice"}, { "data": "status"} ] }); 

This is the JSON object returned from the server:

 { "data": [ { "car": 190, "card_number": "6395637", "invoice": 200, "status": "success" }, { "car": 191, "card_number": "9473650", "invoice": 180, "status": "success" } ], "balance": 7300 } 

As you can see, the data parameter of the returned JSON object is used by the datatables function to populate the datatables, and now I want to parse the balance parameter, but I cannot. How can I achieve this?

+6
source share
3 answers

Something like that:

 $('#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

+18
source

Do not use the DataTable URL function, make an Ajax call itself

 $.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 }); 
+5
source

Since DataTables 1.10 you can use the ajax.json() function: https://datatables.net/reference/api/ajax.json () I implemented it in the example 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. To do this, you need to initialize the datatable with $('#location-table').DataTable() , not $('#location-table').dataTable (the difference is in the capital D)

0
source

Source: https://habr.com/ru/post/986739/


All Articles