How to Create AJAX Pagination in CodeIgniter

AJAX based pagination load content without reloading the whole webpage and improve the user experience.

CodeIgniter has the pagination library to add pagination.

From the controller need to handle the AJAX request which sends from the view.

In this tutorial, I show how you can create AJAX pagination in CodeIgniter.

How to Create AJAX Pagination in CodeIgniter


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Demo
  7. 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 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 3 methods –

  • __construct() – Load url helper, pagination library and Main_model model.
  • index() – Load user_view view.
  • loadRecord() – This method call from $.ajax request.

Fetch records and the total number of records from Main_model. Configure pagination and initialize $data Array.

Encode $data in JSON format for return.

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 Pagination library
    $this->load->library('pagination');

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

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

  public function loadRecord($rowno=0){

    // Row per page
    $rowperpage = 5;

    // 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

HTML

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

Create a <table id='postsList'> and <div id='pagination'>.

Display pagination links in <div id='pagination'> with jQuery and records in <table id='postsList'> <tbody>.

jQuery

Here, create two functions –

  • loadPagination() – Send AJAX request to <?=base_url()?>index.php/User/loadRecord/ where pass the pagno.

On successful callback add response.pagination in $('#pagination') and call createTable() function to list records in <table id='postsTable'> where pass the response.result and response.row.

  • createTable() – Empty the <table id='postsList'> <tbody>.

Loop on the result and create <tr>.

Append <tr> in $('#postsList tbody').

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <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);
     });

     loadPagination(0);

     // 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. Demo

Open in a new tab.


7. Conclusion

Create a method in the controller to load data and pagination links. From view send jQuery AJAX to the created controller method and handle the JSON response to display records and pagination.

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