2

My AJAX call gets JSON data which can sometimes be empty. If I set the paginate option to true, the search and pagination components are shown even if I have 0 results. In which case I set the data to an empty object as [{}]. My settings are as follows:

processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
searching:true,
lengthChange:false,
info: false

The JSON as follows:

draw: 1
length: 10
recordsFiltered: 10
recordsTotal: 1
start: 0
data: [..... list of items]

How to disable these two components if I have no data?

Update: I am not trying to change a setting after render, I am simply not able to understand why is Datatable showing pagination if the results are 0 and is there a way to avoid it. Currently I have hidden it using the xhr event to check the length of the data.

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • @SinanSamet Yes, I have seen that answer already, read my update please. I am NOT TRYING TO CHANGE A SETTING! – Rutwick Gangurde Oct 22 '19 at 11:55
  • 1
    Ah okay, taking that into account it seems like this would be the best solution possible for you: https://stackoverflow.com/a/38853805/1421775. Does that one help? – Sinan Samet Oct 22 '19 at 12:18
  • Perfect, that seems a bit more neat than what I am doing. I check the length of the data in the `xhr` event and hide the pagination and search DOM elements using jQuery. You can add that as an answer, I will accept it. However I wonder how a library like this doesn't handle this on its own. – Rutwick Gangurde Oct 22 '19 at 12:35
  • Yes, it's been there for ages I would expect that too. – Sinan Samet Oct 23 '19 at 07:08

1 Answers1

3

Based on this answer you have to use the drawCallback option to find out how many pages exist. You can then hide the pagination when the pages are equal to 1.

BitOfUniverse:

Use drawCallback option to handle DT draw event and show/hide pagination control based on available pages:

$('#table_id').dataTable({
  drawCallback: function(settings) {
    var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
    pagination.toggle(this.api().page.info().pages > 1);
  }
})
Sinan Samet
  • 6,432
  • 12
  • 50
  • 93