1
votes

I am trying to make datatables play well with my rest API. Let me just state right of the bat: "The REST api will not be changed!.

When using serverside processing, datatables wants to send specific query parameters and expects to get back a specific format. This, to me, is bullocks. Noone wants to modify their backend to match the convention of a third party library (although, I suppose, it is great that there is a default provided).

I have set up my table like so:

{
    "processing": true,
    "serverSide": true,
    "ajax": {
      "url": "/api/customers/",
      "dataSrc": "results",
      "data": function (data, settings) {
        // Modify query parameters to match my API
        data.page = ...
        data.page_size = ...
        return data
      }
    },
    ...
}

As you can tell, i have used the ajax.data property to govern what the table requests from the API. This is great. works like a charm. When the response returns, it looks like this

{
    "count": 85,
    "next": "http://myurl.com/?page=2",
    "previous": null,
    "results": [
        ...  // The actual data
    ]
}

From my configuration, you can tell that I use ajax.dataSrc to have the table pick up the results property, but I can't find any documentation regarding how to pick up pagination info from my response. I have tried modifying my configuration to

{
    ...
    "ajax": {
      "url": "/api/customers/",
      "dataSrc": function(data) {
          return {
              recordsTotal: data.count,
              recordsFiltered: ...,
              data: data.results,
              ...
          }
      },
      ...
    },
    ...
}

But that just threw an error. Does not seem to be possible... So then, what can I do?

1

1 Answers

1
votes

You are correct - this isn't possible using the ajax.dataSrc option. It tells DataTables where to get the data for the rows (data.results in your example), but there is no way using ajax.dataSrc to tell it where to get the recordsTotal etc.

For that you need to use the ajax option as a function - make your Ajax call and return an object. Basically similar to what you are doing already, but you call $.ajax as well.