Ankit Popli Ankit Popli - 4 months ago 78
Ajax Question

DataTables: Custom Response Handling

I started working on

and
DataTables
and wonder whether it is possible to customize the response
DataTables
is expecting. The current expectation of the DataTables plugin is something like this:

{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 5,
"data": [...]
}


On the server end, the API's are being handled by
django-tastypie


The response from server is:

{
meta: {
limit: 20,
next: null,
offset: 0,
previous: null,
total_count: 2
},

objects: [...]
}


So, is there a way to tweak Datatables Plugin to accept/map this response, or I'll have to find a way to add expected fields to the api?

So far I've done this:

var deptTable = angular.element('#deptManagementTable').DataTable({
processing: true,
serverSide: true,
pagingType: "simple_numbers",
ajax: {
url: "/client/api/v1/departments/",
data: function(d) {
d.limit = d.length;
d.offset = d.start;
d.dept_name__icontains = d.search.value;
},
dataSrc: function(json) {
for (var i=0, len=json.objects.length ; i<len ; i++) {
json.objects[i].DT_RowId = json.objects[i].dept_id;
}
return json.objects;
}
},
aLengthMenu: [
[5, 25, 50, 100],
[5, 25, 50, 100]
],
iDisplayLength: 5,
columns: [
{
data: "dept_name"
},
{
data: "dept_created_on",
render: function ( data, type, full, meta ) {
var dateCreated = new Date(data);
dateCreated = dateCreated.toLocaleDateString();
return dateCreated;
}
}
]
});


Any help will be appreciated.

Thanks in Advance :)

Answer

You can pass a function to the DataTables ajax option, this will give you full control over how to fetch and map the data before passing it to DataTables.

.DataTable({
    serverSide: true,
    ajax: function(data, callback, settings) {
        // make a regular ajax request using data.start and data.length
        $.get('/client/api/v1/departments/', {
            limit: data.length,
            offset: data.start,
            dept_name__icontains: data.search.value
        }, function(res) {
            // map your server's response to the DataTables format and pass it to
            // DataTables' callback
            callback({
                recordsTotal: res.meta.total_count,
                recordsFiltered: res.meta.total_count,
                data: res.objects
            });
        });
    }
});

The solution above has been tested with jQuery DataTables 1.10.4.


As this question is tagged with Angular, here's a solution for those using angular-datatables.

<div ng-controller="testCtrl">
    <table datatable dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table>
</div>

.controller('testCtrl', function($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('serverSide', true)
        .withOption('ajax', function(data, callback, settings) {
            // make an ajax request using data.start and data.length
            $http.get('/client/api/v1/departments/', {
                limit: data.length,
                offset: data.start,
                dept_name__icontains: data.search.value
            }).success(function(res) {
                // map your server's response to the DataTables format and pass it to
                // DataTables' callback
                callback({
                    recordsTotal: res.meta.total_count,
                    recordsFiltered: res.meta.total_count,
                    data: res.objects
                });
            });
        })
        .withDataProp('data'); // IMPORTANT¹

    $scope.dtColumns = [
        // your column definitions here
    ];
});

The solution above has been tested with angular-datatables 0.3.0 + DataTables 1.10.4.

¹ The important part to note here is that the angular-datatables solution requires .withDataProp('data') to work, while the pure jQuery DataTables solution does not have a data: 'data' option.

Comments