Ajax Pagination with Search and Filter in CodeIgniter

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.

  • Fetch records from the database and listed on the web page.
  • Add Ajax pagination to the data list.
  • Add search and filter options to the list.
  • Loader image on Ajax request processing.

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/

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

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.

Controller (Posts.php)

The Posts controller handles the data loading process by the pagination links.

  • __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 the Post model.
    • Specify the configurations in $config array for pagination class.
    • In the link_func option, specify the function name (searchFilter) that handles search functionality using jQuery.
    • 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 pagination links.
    • Define offset by the page number.
    • Specify the search keywords and filter option.
    • Fetch the posts data based on the offset and limit.
    • Initialize the Pagination class with the custom search function.
    • Load post 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;
        
$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'$datafalse);
    }
}

Model (Post.php)

The Post model handles the database related operations.

  • getRows()
    • Fetch the records from posts table based on the conditions provided in the $params array.
    • The 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;
    }
}

View (posts/)

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.

  • The searchFilter() method loaded by the pagination links.
  • Retrieve the value from the search field and filter dropdown.
  • Send search keywords and filter options to the ajaxPaginationData() function of Posts controller using jQuery and Ajax.
  • Based on the Ajax response, filtered records are displayed in the post list.
<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:

  • Use create_links() function of Ajax Pagination class to render the pagination links.
  • Use the searchFilter() function with onkeyup / onchange event to trigger the search operation.
  • Specify the element to display the loading image when the Ajax request is initiated for data loading.
<!-- 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

Conclusion

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

13 Comments

  1. Eric Said...
  2. Peter R Said...
  3. Imran Said...
  4. Eddie Said...
  5. Farid Said...
  6. Mike Romero Said...
  7. Khan Said...
  8. Faizan Javaid Said...
  9. Aziz Sudrajat Said...
  10. Dan M Said...
  11. Dan M Said...
  12. Matteus Sousa Said...

Leave a reply

keyboard_double_arrow_up