Datatables bringing all data at once

Asked

Viewed 518 times

1

I have a bizarre problem that’s making me pull my hair out, I know I’m creating a valid json via server side, I even used a json validator. the format of my json is that way:

[
 {
   "name": "jhon doe",
   "age": "22",
   "eye": "brown"
 },
 {
   "name": "amanda",
   "age": "26",
   "eye": "blond"
 }
]

By instantiating the datatables, it brings me all the results at once. not page, and the option to filter so that only 10 results come at a time also does not work. here’s my javascript code:

$('#list_table').DataTable({
            processing: true,
            serverSide: true,
            language: language,
            ajax: {
                url: 'myurl.dev/fetchdata',
                dataType: 'json',
                dataSrc: ''
            },
            columns: [
                { data: "name" },
                { data: "age" },
                { data: "eye" }         
            ],

            responsive: true,
            autoWidth: false,
            order: [0, 'desc'],
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
        });

when checking the network tab -> XHR. I see that the answer brings me the result like this:aba network do chrome

what else can I do to make it work properly? is the first time I’m dealing with this problem using datatables.

1 answer

1

Change the variable serverSide: true for false. When you say the serverSide is false, your web service must deliver pagination data.

This would be a valid return taken from the Datatable documentation, see in this link:

{
    "draw": 1,
    "recordsTotal": 57,
    "recordsFiltered": 57,
    "data": [
    [
        "Airi",
        "Satou",
        "Accountant",
        "Tokyo",
        "28th Nov 08",
        "$162,700"
    ],
}

In short, just change serverside to false.

See a functional example:

$(document).ready(function() {
  $('#table_id').DataTable({

    processing: true,
    serverSide: false,
    ajax: {
      url: 'https://jsonplaceholder.typicode.com/posts',
      dataType: 'json',
      dataSrc: ''
    },
    columns: [{
        data: "id"
      },
      {
        data: "title"
      },
      {
        data: "body"
      }
    ],

    lengthMenu: [
      [1, 5, 15, -1],
      [1, 5, 15, "All"]
    ]
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.1/js/jquery.dataTables.min.js"></script>


<table id="table_id" class="display">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Body</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.