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.

4
  • @SinanSamet Yes, I have seen that answer already, read my update please. I am NOT TRYING TO CHANGE A SETTING! Commented Oct 22, 2019 at 11:55
  • 1
    Ah okay, taking that into account it seems like this would be the best solution possible for you: stackoverflow.com/a/38853805/1421775. Does that one help? Commented Oct 22, 2019 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. Commented Oct 22, 2019 at 12:35
  • Yes, it's been there for ages I would expect that too. Commented Oct 23, 2019 at 7:08

1 Answer 1

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);
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.