Ajax Pagination in CodeIgniter Framework

CodeIgniter has a built-in Pagination library that helps to add pagination functionality in the data list. With this CodeIgniter Pagination class, the page is refreshed when the data is loaded by the pagination links. If you want to integrate the pagination feature without reloading page, ajax based pagination is the best option.

CodeIgniter Ajax Pagination provides a user-friendly interface for the data list of your web application. You can easily build the Ajax pagination functionality with the Pagination class in CodeIgniter. In this tutorial, we will show you how to create pagination links and add to the data list in the CodeIgniter framework.

In the example Ajax Pagination script, we will add the pagination links to the posts data list. The following functionality will be implemented to demonstrate Ajax pagination in CodeIgniter application.

  • Fetch posts data from the database and list them on the web page.
  • Create pagination links and add them to the data list.
  • Load data by the pagination link without page reload using jQuery and Ajax.
  • Loader image on data processing.

Before getting started to integrate Ajax pagination in CodeIgniter, take a look at the files structure.

codeigniter_ajax_pagination/
├── application/
│   ├── controllers/
│   │   └── Posts.php
│   ├── libraries/
│   │   └── Ajax_pagination.php
│   ├── models/
│   │   └── Post.php
│   └── views/
│       └── posts/
│           ├── index.php
│           └── ajax-data.php
└── assets/
    ├── js/
    │   └── jquery.min.js
    ├── css/
    │   └── style.css
    └── images/

Create Database Table

To store the dynamic data a table is required in the database. The following SQL creates a posts table in the MySQL database.

CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Ajax Pagination Library

We’ll use the CodeIgniter’s Pagination class to build Ajax pagination library for CodeIgniter application. This Ajax Pagination library helps to generate pagination links and load data without page refresh using jQuery & Ajax. This custom library provides various configuration options to customize the pagination in CodeIgniter. Some useful options are given below.

  • Display a loading image while data loading.
  • Add a custom function to pagination links.
  • Set a selector to load the pagination data.
  • and many more.

The Ajax Pagination library file (Ajax_pagination.php) needs to be placed in the application/libraries/ directory of the CodeIgniter application. You don’t need to download this library separately, it included in the source code.

Controller (Posts.php)

The Posts controller handles data loading and pagination functionality.

  • __construct()
    • Load the Ajax Pagination library.
    • Load the Post model.
    • Define the limit of records to display per page.
  • index()
    • Get the count of total records using the getRows() method of Post model.
    • Specify the configurations in $config array for pagination class.
    • Initialize the Ajax Pagination class using initialize() method.
    • Fetch records from the database using getRows() method of Post model.
    • Pass the posts data and load the list view.
  • ajaxPaginationData()
    • This function is loaded by the Ajax request.
    • Define offset by the page number.
    • Fetch the posts data based on the offset and limit.
    • Initialize pagination class and create links.
    • Load the posts data with pagination links.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
Posts extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
// Load pagination library
        
$this->load->library('ajax_pagination');
        
        
// Load post model
        
$this->load->model('post');
        
        
// Per page limit
        
$this->perPage 4;
    }
    
    public function 
index(){
        
$data = array();
        
        
// Get record count
        
$conditions['returnType'] = 'count';
        
$totalRec $this->post->getRows($conditions);
        
        
// Pagination configuration
        
$config['target']      = '#dataList';
        
$config['base_url']    = base_url('posts/ajaxPaginationData');
        
$config['total_rows']  = $totalRec;
        
$config['per_page']    = $this->perPage;
        
        
// Initialize pagination library
        
$this->ajax_pagination->initialize($config);
        
        
// Get records
        
$conditions = array(
            
'limit' => $this->perPage
        
);
        
$data['posts'] = $this->post->getRows($conditions);
        
        
// Load the list page view
        
$this->load->view('posts/index'$data);
    }
    
    function 
ajaxPaginationData(){
        
// Define offset
        
$page $this->input->post('page');
        if(!
$page){
            
$offset 0;
        }else{
            
$offset $page;
        }
        
        
// Get record count
        
$conditions['returnType'] = 'count';
        
$totalRec $this->post->getRows($conditions);
        
        
// Pagination configuration
        
$config['target']      = '#dataList';
        
$config['base_url']    = base_url('posts/ajaxPaginationData');
        
$config['total_rows']  = $totalRec;
        
$config['per_page']    = $this->perPage;
        
        
// Initialize pagination library
        
$this->ajax_pagination->initialize($config);
        
        
// Get records
        
$conditions = array(
            
'start' => $offset,
            
'limit' => $this->perPage
        
);
        
$data['posts'] = $this->post->getRows($conditions);
        
        
// Load the data list view
        
$this->load->view('posts/ajax-data'$datafalse);
    }
}

Model (Post.php)

The Post model handles the database related operations.

  • getRows() – Fetch the records from the posts table based on the conditions provided in the $params array.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
Post extends CI_Model{
    
    function 
__construct() {
        
// Set table name
        
$this->table 'posts';
    }
    
    
/*
     * Fetch records from the database
     * @param array filter data based on the passed parameters
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->table);
        
        if(
array_key_exists("where"$params)){
            foreach(
$params['where'] as $key => $val){
                
$this->db->where($key$val);
            }
        }
        
        if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            
$result $this->db->count_all_results();
        }else{
            if(
array_key_exists("id"$params) || (array_key_exists("returnType"$params) && $params['returnType'] == 'single')){
                if(!empty(
$params['id'])){
                    
$this->db->where('id'$params['id']);
                }
                
$query $this->db->get();
                
$result $query->row_array();
            }else{
                
$this->db->order_by('id''desc');
                if(
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit'],$params['start']);
                }elseif(!
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit']);
                }
                
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }
        
        
// Return fetched data
        
return $result;
    }
}

View (posts/)

The posts/ directory holds the view files of the Posts controller.

1. index.php
In the index.php file, the limited number of posts are listed with the pagination links.

  • Include the jQuery library to use Ajax functionality.
  • Use create_links() function of Ajax Pagination class to render the pagination links.
  • Specify the element to display the loading image when the post data is retrieved via Ajax.
  • If you wish to change the loading element, set the selector in the pagination configuration option ($config['loading']).
<!DOCTYPE HTML>
<html lang="en">
<head>
    <title>CodeIgniter Pagination by CodexWorld</title>
	
    <!-- Stylesheet file -->
    <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>" />
	
    <!-- jQuery library -->
    <script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
</head>
<body>
<div class="container">
    <h1>Data List with Ajax Pagination</h1>
	
    <div class="row">
        <div class="post-list" id="dataList">
            <!-- Display posts list -->
            <?php if(!empty($posts)){ foreach($posts as $row){ ?>
                <div class="list-item"><a href="#"><?php echo $row["title"]; ?></a></div>
            <?php } }else{ ?>
                <p>Post(s) not found...</p>
            <?php ?>
			
            <!-- Render pagination links -->
            <?php echo $this->ajax_pagination->create_links(); ?>
        </div>
		
        <!-- Loading Image -->
        <div class="loading" style="display: none;">
            <div class="content"><img src="<?php echo base_url('assets/images/loading.gif'); ?>"/></div>
        </div>
    </div>
</div>
</body>
</html>

2. ajax-data.php
The ajax-data.php does the same operations as the index.php. But this view only displays the posts list with Ajax pagination links.

<!-- Display posts list -->
<?php if(!empty($posts)){ foreach($posts as $row){ ?>
	<div class="list-item"><a href="#"><?php echo $row["title"]; ?></a></div>
<?php } }else{ ?>
	<p>Post(s) not found...</p>
<?php ?>

<!-- Render pagination links -->
<?php echo $this->ajax_pagination->create_links(); ?>

Ajax Pagination with Search and Filter in CodeIgniter

Conclusion

Our Ajax Pagination class provides an easy way to integrate pagination in CodeIgniter without page reload. If you want to improve the UI of your CodeIgniter application, Ajax pagination is the best option to add pagination in the data list. Also, you can enhance the functionality of the CodeIgniter Ajax Pagination library as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

20 Comments

  1. Irfan Said...
  2. Ann Said...
    • CodexWorld Said...
  3. Ronaldus Cricri Said...
  4. Shibnath Roy Said...
  5. Iftikhar Said...
    • CodexWorld Said...
  6. Affan Said...
  7. Kailash Jangir Said...
  8. Abdul Muin Amz Said...
  9. Yasser Said...
  10. Tony Said...
  11. Federico Said...
    • CodexWorld Said...
  12. Federico Said...
    • CodexWorld Said...
  13. Federico Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up