Skip to main content

Create Ajax Pagination in CodeIgniter with Example

Pagination is a feature of web applications to load large dynamic data into multiple pages by displaying next and previous link to view dynamic data.

As a PHP developer, you have definitely implemented pagination with PHP and now looking for implementing pagination in CodeIgniter. It’s very easy to implement pagination in CodeIgniter as it has default Pagination class to implement pagination but it’s not user friendly.

So here in this tutorial you will learn how to implement Ajax pagination in CodeIgniter framework. The pagination with Ajax is simple and user friendly can be used in any CodeIgniter project.

We will cover this tutorial in easy steps with live demo to implement Ajax based pagination in CodeIgniter. You can also download complete source of live demo.

Also, read:

As CodeIgniter has Pagination class to create pagination, so we will use this pagination class to create dynamic pagination. Now here we will create dynamic Ajax pagination with in CodeIgniter in easy steps.

We hope that you have setup your CodeIgniter application with database connection details to use with this example. So let’s start.

Step1: Create MySQL Database Table

As we will create pagination with dynamic data, so first we will create MySQL database table developers using below table create query.

CREATE TABLE `developers` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `skills` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `designation` varchar(255) NOT NULL,
  `age` int(11) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

We will also insert few records using below insert query.

INSERT INTO `developers` (`id`, `name`, `skills`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(1, 'Smith', 'Java', 'Newyork', 'Male', 'Software Engineer', 34, 'image_1.jpg'),
(2, 'David', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(3, 'Rhodes', 'jQuery', 'New Jersy', 'Male', 'Web Developer', 30, 'image_2.jpg'),
(4, 'Sara', 'JavaScript', 'Delhi', 'Female', 'Web Developer', 25, 'image_2.jpg'),
(5, 'Shyrlin', 'NodeJS', 'Tokiyo', 'Female', 'Programmer', 35, 'image_2.jpg'),
(6, 'Steve', 'Angular', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(7, 'Cook', 'MySQL', 'Paris', 'Male', 'Web Developer', 26, 'image_2.jpg'),
(8, 'Root', 'HTML', 'Paris', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(9, 'William', 'jQuery', 'Sydney', 'Male', 'Web Developer', 23, 'image_2.jpg'),
(10, 'Nathan', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(11, 'Shri', 'PHP', 'Delhi', 'Male', 'Web Developer', 38, 'image_2.jpg'),
(12, 'Jay', 'PHP', 'Delhi, India', 'Male', 'Web Developer', 30, 'image_3.jpg');

Step2: Create Models for Employee Data

Now we will create models file Emp_model.php in application/models directory. The Emp_model has function getRecord() to get pagination records from developers table and a function getRecordCount() to get total record count.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Emp_model extends CI_Model {
	public function __construct() {
		parent::__construct(); 
	}
	public function getRecord($rowno,$rowperpage) {			
		$this->db->select('*');
		$this->db->from('developers');
        $this->db->limit($rowperpage, $rowno);  
		$query = $this->db->get();       	
		return $query->result_array();
	}
	public function getRecordCount() {
    	$this->db->select('count(*) as allcount');
      	$this->db->from('developers');
      	$query = $this->db->get();
      	$result = $query->result_array();      
      	return $result[0]['allcount'];
    }
}

Step3: Create Controllers

Now we will create controllers Employee.php in application/controllers directory. The controllers will load URL helper, pagination library and Emp_model models. The controllers has function index() to load employee data and function loadData() that’s called from Ajax request and get employee data from models Emp_model using models function getRecord() and configure pagination options and initialize data array and return data as JSON.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Employee extends CI_Controller {
	public function __construct(){		
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('pagination');
		$this->load->model('Emp_model');
	}
	public function index(){
		$this->load->view('employee');
	}
	public function loadData($record=0) {
		$recordPerPage = 5;
		if($record != 0){
			$record = ($record-1) * $recordPerPage;
		}      	
      	$recordCount = $this->Emp_model->getRecordCount();
      	$empRecord = $this->Emp_model->getRecord($record,$recordPerPage);
      	$config['base_url'] = base_url().'index.php/Employee/loadData';
      	$config['use_page_numbers'] = TRUE;
		$config['next_link'] = 'Next';
		$config['prev_link'] = 'Previous';
		$config['total_rows'] = $recordCount;
		$config['per_page'] = $recordPerPage;
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		$data['empData'] = $empRecord;
		echo json_encode($data);		
	}
}

Step4: Create Views to Load Record with Pagination

Now we will create views employee.php in application/views directory. Here we will create HTML to load dynamic pagination data with Ajax response.

<div class="container">
	<div class="row ">
		<table id='employeeList' class="table table-bordered">
			<thead>
			<tr>
				<th>EmpId</th>
				<th>Name</th>
				<th>Age</th>
				<th>Skills</th>
				<th>Designation</th>
				<th>Address</th>
			</tr>
			</thead>
			<tbody></tbody>
		</table>
		<div id='pagination'></div>	
	</div>
</div>

Step5: Make Ajax Request and Load Data with Pagination

We will also need to use jQuery code in views employee.php in application/views directory to load pagination and make Ajax request to load more records.

<script type='text/javascript'>
$(document).ready(function() {
	createPagination(0);
	$('#pagination').on('click','a',function(e){
		e.preventDefault(); 
		var pageNum = $(this).attr('data-ci-pagination-page');
		createPagination(pageNum);
	});
	function createPagination(pageNum){
		$.ajax({
			url: '<?=base_url()?>index.php/Employee/loadData/'+pageNum,
			type: 'get',
			dataType: 'json',
			success: function(responseData){
				$('#pagination').html(responseData.pagination);
				paginationData(responseData.empData);
			}
		});
	}
	function paginationData(data) {
		$('#employeeList tbody').empty();
		for(emp in data){
			var empRow = "<tr>";
			empRow += "<td>"+ data[emp].id +"</td>";
			empRow += "<td>"+ data[emp].name +"</td>";
			empRow += "<td>"+ data[emp].age +"</td>"
			empRow += "<td>"+ data[emp].skills +"</td>"
			empRow += "<td>"+ data[emp].designation +"</td>"
			empRow += "<td>"+ data[emp].address +"</td>";
			empRow += "</tr>";
			$('#employeeList tbody').append(empRow);					
		}
	}
});
</script>

Step6: Application Configuration

We will also need following application configuration to run this example.

  • Need to open application/config/routes.php and edit default_controller value to employee.
    $route['default_controller'] = 'employee';
  • Need to open config/config.php and edit $config['base_url'] with your project url value to your project:
    $config['base_url'] = 'http://localhost/your_codeigniter_project/';

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

4 thoughts on “Create Ajax Pagination in CodeIgniter with Example

Comments are closed.