Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset pagination in a JQuery datatable

I have a JQuery datatable that loads data via an ajax request. There is a form by the table that lets the user filter the results on the server. When the user changes the filter form, I call fnReloadAjax() with the new filter data, and the table redraws with the new, filtered results.

The problem I have is that the pagination sticks, even if the table no longer has enough items to reach the current page. So if the table originally had 20 items, and the user was on page 2 (10 items per page), and they change the filter so only 5 items are returned, the table displays no items and shows this at the bottom:

Showing 11 to 5 of 5 entries

It's still on page 2 even though there is only enough data for one page.

I have found numerous posts about trying to preserve the current page/row, but none showing a simple way to reset pagination to the first page. What is the simplest way to do this?

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

$("#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;
});
like image 200
JMB Avatar asked Sep 04 '13 00:09

JMB


3 Answers

You could explicitly jump to the first page after reloading, see http://datatables.net/api#fnPageChange

$("#myForm").submit(function(e) {
    table.fnPageChange(0);
    table.fnReloadAjax();
    return false;
});
like image 127
Gigo Avatar answered Nov 14 '22 06:11

Gigo


Accepting the solution given by @Gigo:

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

This have a problem, it sends two request to the server.

i have found that the fnPageChange does it at the first time.

$("#myForm").submit(function(e) {
    table.fnPageChange(0);
    return false;
});
like image 29
workdreamer Avatar answered Nov 14 '22 06:11

workdreamer


This can be solved by implementing the functions to save and load the state of the datatable and resetting the start point - 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
  },

As fnStateLoad is called when the table is reloaded - e.g. a new filter is applied - the paging is reset to the start.

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

This approach avoids the overhead of an additional request back to the server

like image 1
RPG II Avatar answered Nov 14 '22 06:11

RPG II