Datatable serverside payload structure

Datatable serverside payload structure

aumartinezaumartinez Posts: 11Questions: 3Answers: 2
edited February 2023 in Free community support

I checked the documentation and implemented Datatables with the serverside option in a project which improved the loading times, however, in a new project I am wondering if the structure on the payload is fixed or if it can be changed, lets say, the Datatable is awaiting for a response like:

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

What if I get a different payload structure? How can I inject the recordsTotal and recordsFiltered required by the Datatable? I used dataSrc option to map the payload to something that is readable by the datable, but I am lost on how to work the other fields.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin

    What DataTables sends and receives by default is documented here.

    You can use the preXhr event to modify the data being submitted (or (ajax.data if you prefer) and the xhr event to modify the data being returned from the server.

    What is the structure you are getting back?

    Allan

  • aumartinezaumartinez Posts: 11Questions: 3Answers: 2
    edited February 2023

    The payload I got has a parameter with the total records received and the data is a bunch of objects with different depth levels like:

    {
      total: 62,
      page: 1,
      quantity: 10,
      data: [
        obj1,
        obj2: {prop1, prop2, prop3},
        obj3: [value1, value2, value]
      ]
    }
    

    The data received I am able to map it into what the Datatable requires using the dataSrc callback and it works fine when serverside is not enabled since all the data is pulled to the datatable in the data array, but with serverside, I am not able to return the rest of required parameters without changing the backend which I don't have access to

  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin
    Answer ✓

    The ajax.dataSrc function can manipulate the JSON at the top level, but must return the array of data to be displayed - e.g.: https://live.datatables.net/pedavoto/1/edit .

    So for example in this case:

    dataSrc: function (json) {
      json.recordsFiltered = json.total;
      json.recordsTotal = json.total;
      return json.data;
    }
    

    Allan

Sign In or Register to comment.