DataTables Example Using an Ajax Callback
ajax option, documented here, is a common way to retrieve dynamic data from a source, for loading into a table.
Typically, I use this option with an object - something like this:
This is basically a wrapper around the jQuery
ajax() API - with the addition of
dataSrc to help DataTables locate its row iteration starting point.
However, you can also use a function with the DataTables
ajax option, instead of an object. The following fragment shows an example:
This approach allows you to process the JSON response from the ajax call, before passing the row array data to DataTables. You can therefore re-arrange the JSON data, and process additional data in the JSON if needed.
In this specific example, the option uses a function. In this case, it’s up to you to make the actual ajax call (e.g. using jQuery’s ajax API, as shown above).
The three parameters made available in this option are:
|The data to be sent to the server.|
|Callback function that must be executed when the required data has been obtained from the ajax request. That data should be passed into the callback as the only parameter.|
|The DataTable settings object.|
In our example the
callback function re-names the data array from
This is needed because DataTables expects the data array to be called
data - and the normal approach (using
dataSrc: 'row_objects') is not available when the ajax function is used.
An example of the JSON handled by the above code is: