Retain AJAX pagination position after Refresh in CodeIgniter

AJAX pagination makes it easier to display the large list of records in multiple pages without refreshing the whole page when navigating.

While navigating pages if you refreshed the webpage then it will load record from 1st instead of page position before the refresh.

E.g. If you are on 5 page then it will again start from 1 when webpage reload.

To retain the position, I am using COOKIE to store the page number and use it after page successfully load to fetch records in CodeIgniter.

Retain AJAX pagination position after Refresh in CodeIgniter


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Conclusion

1. Table structure

I am using posts table.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Model

Create a new Main_model.php file in application/models/ directory.

Create 3 methods –

  • __construct() – Constructor.
  • getData() – Fetch records from posts table and use $rowno, $rowperpage to limit records. Return an Array of records.
  • getrecordCount() – Count total records in posts table and return allcount.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Main_model extends CI_Model {

  public function __construct() {
    parent::__construct(); 
  }

  // Fetch records
  public function getData($rowno,$rowperpage) {
 
    $this->db->select('*');
    $this->db->from('posts');
    $this->db->limit($rowperpage, $rowno);  
    $query = $this->db->get();
 
    return $query->result_array();
  }

  // Select total records
  public function getrecordCount() {

    $this->db->select('count(*) as allcount');
    $this->db->from('posts');
    $query = $this->db->get();
    $result = $query->result_array();
 
    return $result[0]['allcount'];
  }

}

4. Controller

Create a new User.php file in application/controllers/ directory.

Create 4 methods –

  • __construct() – Load url, cookie helper, pagination library, Main_model model.
  • index() – Load user_view view.
  • getPaginationPosition() – This method call from jQuery AJAX request to get the position after page load from COOKIE.

If COOKIE is not set then return 0.

  • loadRecord() – This method also call from jQuery AJAX request. Initialize COOKIE with $rowno. While setting COOKIE adjust the expire time according to your requirement I set it for 2 hours (7200 sec).

Count total records and fetch records.

Configure pagination and initialize $data Array.

Return JSON response.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct(){

    parent::__construct();
    $this->load->helper('url');

    // Load cookie helper
    $this->load->helper('cookie');

    // Load Pagination library
    $this->load->library('pagination');

    // Load model
    $this->load->model('Main_model');
  }

  public function index(){
    $this->load->view('user_view');
  }

  // Read cookie
  public function getPaginationposition(){
    $pageno = 0;
    if($this->input->cookie('pageno') != null){
      $pageno =$this->input->cookie('pageno');
    } 
    echo $pageno;
  }

  public function loadRecord($rowno=0){

    // Row per page
    $rowperpage = 5;

    // Set cookie
    $cookie= array(
     'name' => 'pageno',
     'value' => $rowno,
     'expire' => 7200,
    );
    $this->input->set_cookie($cookie);

    // Row position
    if($rowno != 0){
      $rowno = ($rowno-1) * $rowperpage;
    }

    // All records count
    $allcount = $this->Main_model->getrecordCount();

    // Get records
    $users_record = $this->Main_model->getData($rowno,$rowperpage);

    // Pagination Configuration
    $config['base_url'] = base_url().'index.php/User/loadRecord';
    $config['use_page_numbers'] = TRUE;
    $config['total_rows'] = $allcount;
    $config['per_page'] = $rowperpage;

    // Initialize
    $this->pagination->initialize($config);

    // Initialize $data Array
    $data['pagination'] = $this->pagination->create_links();
    $data['result'] = $users_record;
    $data['row'] = $rowno;

    echo json_encode($data);

  } 

}

5. View

Create a new user_view.php file in application/views/ directory.

HTML –

Create <table > to display records using jQuery and display pagination navigation links in <div id='pagination'></div>.

Script –

Create 3 functions –

  • getPosition() – Send an AJAX request to get page number. On successful callback assign response to pageno and pass it in loadPagination(pageno).
  • loadPagination() – Send an AJAX request to fetch records according to pageno value. On successful callback pass response.pagination in $('#pagination').html() and call createTable() function to create new tables rows where pass response.result and response.row.
  • createTable() – Empty the <tbody> and loop on the result to create new <tr> and append in <tbody>.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Retain AJAX pagination position after Refresh in CodeIgniter</title>

    <style type="text/css">
    a {
      padding-left: 5px;
      padding-right: 5px;
      margin-left: 5px;
      margin-right: 5px;
    } 
    </style>
  </head>
  <body>

    <!-- Posts List -->
   <table border='1' width='100%' style='border-collapse: collapse;' id='postsList'>
    <thead>
     <tr>
      <th>S.no</th>
      <th>Title</th>
      <th>Content</th>
     </tr>
    </thead>
    <tbody></tbody>
   </table>

   <!-- Paginate -->
   <div style='margin-top: 10px;' id='pagination'></div>
    
   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type='text/javascript'>
   $(document).ready(function(){

     // Detect pagination click
     $('#pagination').on('click','a',function(e){
       e.preventDefault(); 
       var pageno = $(this).attr('data-ci-pagination-page');
       loadPagination(pageno);
     });

     getPosition();

     // Get page number from cookie
     function getPosition(){
       $.ajax({
        url: '<?=base_url()?>index.php/User/getPaginationposition/',
        type: 'get',
        success: function(response){
          var pageno = response;
          // Load pagination
          loadPagination(pageno);
        }
      });
    }

    // Load pagination
    function loadPagination(pagno){
      $.ajax({
        url: '<?=base_url()?>index.php/User/loadRecord/'+pagno,
        type: 'get',
        dataType: 'json',
        success: function(response){
          $('#pagination').html(response.pagination);
          createTable(response.result,response.row);
        }
      });
    }

    // Create table list
    function createTable(result,sno){
       sno = Number(sno);
       $('#postsList tbody').empty();
       for(index in result){
         var id = result[index].id;
         var title = result[index].title;
         var content = result[index].content;
         content = content.substr(0, 60) + " ...";
         var link = result[index].link;
         sno+=1;

         var tr = "<tr>";
         tr += "<td>"+ sno +"</td>";
         tr += "<td><a href='"+ link +"' target='_blank' >"+ title +"</a></td>";
         tr += "<td>"+ content +"</td>";
         tr += "</tr>";
         $('#postsList tbody').append(tr);

       }
     }
   });
   </script>
 </body>
</html>

6. Conclusion

Use COOKIE to store position whenever position changes. On page refresh check COOKIE value using AJAX request and use it to load records.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *