Ajax Pagination in CodeIgniter provides a user-friendly way to add pagination links to the data list. Search functionality is very useful to make the data list more user-friendly. The search feature helps to filter and find the specific records quickly from the huge number of data. With the Ajax search, you can filter records from the data list without page reload.
In our earlier tutorial, we have provided a step-by-step guide to integrate Ajax pagination in CodeIgniter web application. Now, we will enhance the functionality of the CodeIgniter Ajax Pagination with search and filter. Search and filtering features are commonly used in the data list. In this tutorial, we will show you how to implement live search and filter on the list with Ajax Pagination in CodeIgniter.
In the example Ajax search script, we will add the pagination and search feature to the posts data list.
Before getting started to integrate Ajax pagination and search functionality in CodeIgniter, take a look at the file structure.
codeigniter_ajax_pagination_search_filter/ ├── 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;
Our custom Ajax Pagination library helps to create pagination links and load data without page reload using jQuery & Ajax in CodeIgniter. The link_func
configuration option allows you to attach the search functionality with Ajax pagination.
The Ajax Pagination library file (Ajax_pagination.php
) is required to place in the application/libraries/
directory of the CodeIgniter application. This library is included in the source code, you don’t need to download this library separately.
Note that: In pagination configuration, a function (searchFilter
) is specified in link_func. This user-defined function will be called on each pagination link, which helps to pass the search and filter request.
The Posts controller handles the data loading process by the pagination links.
getRows()
method of the Post model.$config
array for pagination class.searchFilter
) that handles search functionality using jQuery.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;
$config['link_func'] = 'searchFilter';
// 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;
}
// Set conditions for search and filter
$keywords = $this->input->post('keywords');
$sortBy = $this->input->post('sortBy');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
if(!empty($sortBy)){
$conditions['search']['sortBy'] = $sortBy;
}
// 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;
$config['link_func'] = 'searchFilter';
// Initialize pagination library
$this->ajax_pagination->initialize($config);
// Get records
$conditions['start'] = $offset;
$conditions['limit'] = $this->perPage;
unset($conditions['returnType']);
$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.search
option indicates to filter the records by title.<?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("search", $params)){
// Filter data by searched keywords
if(!empty($params['search']['keywords'])){
$this->db->like('title', $params['search']['keywords']);
}
}
// Sort data by ascending or desceding order
if(!empty($params['search']['sortBy'])){
$this->db->order_by('title', $params['search']['sortBy']);
}else{
$this->db->order_by('id', 'desc');
}
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
Initially, the limited number of posts are listed with the pagination links. Also, a search input field and sort by the select box are added to the list.
jQuery Library:
Include the jQuery library, it required for Ajax pagination and search functionality.
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
Custom Search JavaScript Function:
Define the custom JavaScript function to handle the search operation.
searchFilter()
method loaded by the pagination links.ajaxPaginationData()
function of Posts controller using jQuery and Ajax.<script>
function searchFilter(page_num){
page_num = page_num?page_num:0;
var keywords = $('#keywords').val();
var sortBy = $('#sortBy').val();
$.ajax({
type: 'POST',
url: '<?php echo base_url('posts/ajaxPaginationData/'); ?>'+page_num,
data:'page='+page_num+'&keywords='+keywords+'&sortBy='+sortBy,
beforeSend: function(){
$('.loading').show();
},
success: function(html){
$('#dataList').html(html);
$('.loading').fadeOut("slow");
}
});
}
</script>
Data List with Pagination and Search:
create_links()
function of Ajax Pagination class to render the pagination links.searchFilter()
function with onkeyup / onchange event to trigger the search operation.<!-- Search form -->
<div class="post-search-panel">
<input type="text" id="keywords" placeholder="Type keywords to filter posts" onkeyup="searchFilter();"/>
<select id="sortBy" onchange="searchFilter();">
<option value="">Sort by Title</option>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
</div>
<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>
2. ajax-data.php
This view is loaded by the Ajax pagination links. It displays only the posts list and the 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(); ?>
CodeIgniter CRUD Operations with Search and Pagination
Our Ajax Pagination library and custom jQuery function provides an easy way to integrate Ajax pagination with search and filter in CodeIgniter framework. For example purpose, we have used only search input and sort by fields, but you can enhance the CodeIgniter Ajax search functionality easily as per your needs.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Hi, great tutorial. Is there any way to make this work with codeigniter 4. Thanks.
Great tool. works perfect.
As i’m using codeigniter 4 i had to to some changes in the script. Let me know if youre interested
thanks for sharing this tutorials i just implement this code but i want multiple search from database like mobile and name then what to do, please suggest.
Thanks in advance.
Awesome! Made it work perfectly! Thanks.
Thanks bro, this work on me
Excellent Work
How to keep the changes, when page is refreshed or when we backup from the page before it..
Your all tutorials are awesome and easy to understand and easy to implement. Your services are appreciated.
Thanks men, this work on me 🙂
In addition to the last question, after you type something and it loads a result, if you erase everything in the keywords box, how do you display nothing?
This seems pretty easy. Wouldd there be a way to not display any items until someone types something into the search box? (Leave the results display completely blank until someone types something in the box to trigger the search?
How to do this same paging with filters using pure php
We’ve recently published a tutorial on how to implement Ajax pagination with search and filter in PHP. Please checkout it from here – http://www.codexworld.com/ajax-pagination-with-search-filter-php/