Search code examples
javascriptjquerydatatablessavestate

Datatables - Keeping only selected page number(not order or search or filter) after callback and clear on refresh


I have a data table which I should change something on it, for example, I want to change the title of the content, but this content is on the 6th page of the table. When I change it, the data table refreshes itself to the 1st page. What I'm trying to do is to keep the selected page number and call it back after refresh. I have tried all solutions but I just want to save page number nothing else. Is that possible?

<script type="text/javascript">
        $(function () {
        var dataTableoOBJ = $("#forumList").dataTable({
        "lengthChange": true,
        "processing": true,
        "serverSide": true,
        "ajax": "/admin/forums/data",
        "createdRow": function (row, data, rowIndex) {
         $.each($('td', row), function (colIndex) {
         $(this).attr('data-id', data.id);
         });
        },
        'columns': [{...}]
        });
        });
</script>

I have also tried

"saveState": true and for clearing state on refresh/reload

if (performance.navigation.type == 1){
   var table = $('#forumList').DataTable();
   table.state.clear();
   table.ajax.reload();
} 

but it's only clearing page numbers is there any way to clear sorting/ordering/searching/filtering?


Solution

  • I've got 2 solutions for this problem.

    Solution 1:

    Add these fields to the data table

     "stateSave": true,
     stateLoadParams: function( settings, data ) {
          var a = data.order;
          if(data.search.search !== '' || a[0][0] !== 0 || data.length !== 10) {
               delete data.order;
               delete data.search;
               delete data.length;
               delete data.start;
               window.location.reload();
           }
           if (data.start === 0) {
               delete data.order;
               delete data.search;
               delete data.length;
               delete data.start;
           }
      }
    

    And required actions for refreshing the page

    if (performance.navigation.type == 1){
         var table = $('#forumList').DataTable();
         table.state.clear();
         table.ajax.reload();
    }
    

    Solution 2:

    Add "stateSave": true field to the data table

    And required actions for refreshing the page

    if (performance.navigation.type == 1){
      var table = $('#forumList').DataTable();
      table.state.clear();
      table.search("").draw(); 
      table.column( '0:visible' ).order( 'asc' ).draw();
      table.page.len(10).draw();
    }