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.
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/
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;
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.
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.
The Posts controller handles data loading and pagination functionality.
getRows()
method of Post model.initialize()
method.getRows()
method of Post model.<?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', $data, false);
}
}
The Post model handles the database related operations.
$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;
}
}
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.
create_links()
function of Ajax Pagination class to render the pagination links.$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
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
this ia great, is there a way we can include search as well?
@Irfan Recently we’ve published CodeIgniter Ajax pagination with search and filter tutorial. It will fulfill your required functionality, see it from here – http://www.codexworld.com/codeigniter-ajax-pagination-with-search-filter/
I have implemented this in my codeigniter 3 application. But the first link is not clickable even if i clicked page 2 or 3. Please suggest me a way to solve this.
@Ann This pagination script already checked with CodeIgniter 3. However, we’ve checked it again and the script is working fine. Please follow our step-by-step instructions.
Very useful. Thanks!!
Btw, is there any way I can use multiple ajax pagination in one page..?
WOw. awesome tutorial. Can you please give me an idea how I can make the current page number persist after page refresh. I know it is something to do with storing some values in session but I am unable to make it work. Please help.
how to show loader image on clicking next page
Regards
iftikhar
@Iftikhar We’ve updated out tutorial and source code with loader image functionality. Please download latest version of the source code.
Very good tutorial . simple and work without any problem . thanks good work
where is ajax_pagination library and how it use in our code file .
@Kailash Download the
Ajax_pagination
library from here – https://app.box.com/s/te737vub29nujnhpmgoplsovdfk0y8ts and placeAjax_pagination.php
file into theapplication/libraries/
directory.nice tutorial.
thanks
I did it, Nice Thread. But I have one problem. I don’t know how to parsing the ajax response. please help me 😀
can you put demo in here?
Thanks for feedback…almost working.
I got in trouble with the configuration….I mean, since the AJAX library is a duplicate of the CI pagination, I’d like to use a configuration file, according to the instruction into the CI3 manual about pagination, and then initialize it using $this->pagination->initialize()
But it doesn’t work on AJAX pagination.
Any hint? Thanks
Hi Federico,
You only needs to initialize ajax pagination library (
$this->ajax_pagination->initialize($config);
). Please follow our tutorial.I’m trying to use your script into my project but I’m not able to get AJAX funcionality into my table. Any way to get some help to understand my faults? Thanks a lot.
Hi Federico,
Please check the jQuery library file has included or not. Because jQuery library is required for ajax pagination.
Great post…exactly what I was looking for. Just an issue…I cannot download the library Ajax_pagination.
Thanks
Thanks Federico.
The download link has been checked and it’s working. We think the problem is occurred at your side. Don’t worry we have sent
Ajax_pagination
library file to your email address. Please check your email and let us know if you need any help.