How to reset pagination in jquery datatable

I have a jQuery datatable that loads data through an ajax request. The table has a form that allows the user to filter the results on the server. When the user changes the shape of the filter, I call fnReloadAjax () with the new filter data, and the table is redrawn with the new filtered results.

The problem is that the folder sticks are located, even if there are no more elements in the table to reach the current page. Therefore, if the table initially had 20 elements and the user was on page 2 (10 elements per page) and they change the filter, so only 5 elements are returned, the table does not display the elements and shows it below:

Showing 11 to 5 of 5 entries 

This is still on page 2, although there is enough data for one page.

I found a lot of messages about trying to save the current page / line, but none of them shows an easy way to reset pagination on the first page. What is the easiest way to do this?

Here's a simplified version of my code for simplification:

 $("#mytable").dataTable({ bStateSave: false, fnServerData: function (sSource, aoData, fnCallback) { return $.ajax({ type: "POST", url: url, data: {filter: filterValue} }); } }); $("#myForm").submit(function(e) { table.fnReloadAjax(); return false; }); 
+4
source share
3 answers

You can explicitly go to the first page after a reboot, see http://datatables.net/api#fnPageChange

 $("#myForm").submit(function(e) { table.fnPageChange(0); table.fnReloadAjax(); return false; }); 
+3
source

This can be solved by implementing the functions of saving and loading the datatable state and resetting the starting point - an example below

  "fnStateSave": function (oSettings, oData) { localStorage.setItem( 'MyDataTable', JSON.stringify(oData) ); }, "fnStateLoad": function (oSettings) { var settings = JSON.parse( localStorage.getItem('MyDataTable') ); settings.iStart = 0; // resets to first page of results return settings }, 

Since fnStateLoad is called when the table is reloaded - for example, a new filter is applied - paging reset to the beginning.

fnStateSave is called every time you retrieve the next page of results

This approach avoids the overhead of an additional server request

+1
source

Making the decision given by @Gigo:

 $("#myForm").submit(function(e) { table.fnPageChange(0); table.fnReloadAjax(); return false; }); 

This has a problem, it sends two requests to the server.

I found fnPageChange to do this for the first time.

 $("#myForm").submit(function(e) { table.fnPageChange(0); return false; }); 
0
source

Source: https://habr.com/ru/post/1500405/


All Articles