AJAX Pagination in CodeIgniter Tutorial

On 3/09/2018

Hi! In this post, we will see how to make ajax pagination in codeigniter using codeigniter pagination library. The Pagination class offers feature rich functions to paginate the query results in view. Although the usage of pagination library is well-documented, paginating the results with jquery ajax is somewhat a mystery. The solutions available around the web are too complicated for beginners. Hence I decided to write a tutorial on the topic that is easy enough for anyone to implement codeigniter pagination with ajax.

For this example, we'll need two libraries which are jQuery and Bootstrap. The jQuery.js is for making ajax call and bootstrap is for designing the user interface.

ajax pagination codeigniter tutorial

CodeIgniter AJAX Pagination Example:

To create ajax pagination, I'm going to use the default pagination library of the code igniter framework. Simply follow the below steps to implement the same.

STEP-1) Create Database

First create the required database, table and the records to use in our example. I'm going to use MySQL here. Just run the following sql queries in mysql and it will take care of DB creation.

CREATE DATABASE `my_demo`;
USE `my_demo`;

CREATE TABLE IF NOT EXISTS `Employees` (
  `EmpID` int(8) NOT NULL AUTO_INCREMENT,
  `EmpName` varchar(50) NOT NULL,
  `DeptName` varchar(30) NOT NULL,
  `Designation` varchar(25) NOT NULL,
  `DOJ` date NOT NULL,
  `Salary` int(10) NOT NULL,
  PRIMARY KEY (`EmpID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

INSERT INTO `Employees` (`EmpID`, `EmpName`, `DeptName`, `Designation`, `DOJ`, `Salary`) VALUES
(1, 'Colleen Hurst', 'HQ', 'Regional Director', '2009-09-15', 205500),
(2, 'Brielle Williamson', 'Software', 'Integration Specialist', '2012-12-02', 372000),
(3, 'Garrett Winters', 'Finance', 'Accountant', '2011-07-25', 170750),
(4, 'Caesar Vance', 'Sales', 'Assistant Manager', '2011-12-12', 106450),
(5, 'Sonya Frost', 'Software', 'Software Engineer', '2008-12-13', 133600),
(6, 'Herrod Chandler', 'Sales', 'Sales Executive', '2012-08-06', 127500),
(7, 'Jena Gaines', 'HQ', 'Manager', '2008-12-19', 112560),
(8, 'Quinn Flynn', 'Software', 'Support Lead', '2013-03-03', 342000);

STEP-2) Create Model

Next, create the codeigniter model to handle database requests. Place this file inside 'application' > 'models' folder. The file contains getEmployees() function to fetch a portion of employees records from the database using the limit condition.

AjaxPaginationModel.php
<?php
class AjaxPaginationModel extends CI_Model {
    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    function getEmployees($limit, $start) {
        $query = $this->db->get('Employees', $limit, $start);
        return $query->result();
    }
}
?>

STEP-3) Create Controller

Next we need a controller file to regulate the interaction between the front-end and the back-end. Create this file inside 'application' > 'controllers' folder.

It contains the default index() function which creates paging links and obtain the employee records from the model function and passes them to the view file.

AjaxPaginationController.php
<?php
class AjaxPaginationController extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('pagination');
        $this->load->model('AjaxPaginationModel');
    }

    function index() {
        //pagination settings
        $config['base_url'] = site_url('AjaxPaginationController/index');
        $config['total_rows'] = $this->db->count_all('Employees');
        $config['per_page'] = '5';
        $config['uri_segment'] = 3;
        $choice = $config['total_rows'] / $config['per_page'];
        $config['num_links'] = floor($choice);
        $this->pagination->initialize($config);

        $data['page'] = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        // fetch employees list
        $data['results'] = $this->AjaxPaginationModel->getEmployees($config['per_page'], $data['page']);       
        // create pagination links
        $data['links'] = $this->pagination->create_links();

        if($this->input->post('ajax')) {
            $this->load->view('Data', $data);
        } else {
            $this->load->view('AjaxPaginationView', $data);
        }
    }
}
?>

STEP-4) Create View

Finally we need to create the view file. This is the user interface where the results from the database will be displayed in a neatly organized table along with pagination links at the bottom.

Please note that to keep this tutorial simple, I haven't styled the pagination links. You can check here to apply bootstrap styles to codeigniter pagination links.

The special thing about the view is that we have split it into two files. One is the main view named 'AjaxPaginationView.php' and the other 'Data.php' that contains the markup to display the ajax data.

AjaxPaginationView.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>CodeIgniter Pagination with AJAX Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="row">
            <h3 class="text-center bg-success">AJAX Pagination in CodeIgniter</h3>
            <div id="ajax_content">
                <?php $this->load->view('Data', $results); ?>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        paginate();
        function paginate() {
            $('#ajax_links a').click(function() {
                var url = $(this).attr('href');
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: 'ajax=true',
                    success: function(data) {
                        $('#ajax_content').html(data);
                    }
                });
                return false;
            });
        }
    });
</script>
</body>
</html>
Data.php
<table class="table table-striped table-hover">
    <thead>
        <tr>
        <th>#</th>
        <th>Emp Name</th>
        <th>Department</th>
        <th>Designation</th>
        <th>Joining Date</th>
        <th>Salary</th>
        </tr>
    </thead>
    <tbody>
    <?php for ($i = 0; $i < count($results); ++$i) { ?>
    <tr>
        <td><?php echo ($page+$i+1); ?></td>
        <td><?php echo $results[$i]->EmpName; ?></td>
        <td><?php echo $results[$i]->DeptName; ?></td>
        <td><?php echo $results[$i]->Designation; ?></td>
        <td><?php echo $results[$i]->DOJ; ?></td>
        <td><?php echo $results[$i]->Salary; ?></td>
    </tr>
    <?php } ?>
    </tbody>
</table>
<div id="ajax_links" class="text-center">
    <?php echo $links; ?>
</div>

In the view file, we have included the java script function to make ajax call and update the data received on the view container.

codeigniter ajax pagination example
Read Also:

Likewise, you can create ajax pagination in codeigniter using the regular pagination class itself. You can also try the 'Ajax Pagination' library offered in the code igniter site. The entire concept is simple and easy to implement. I hope you find this tutorial useful. Please share it on social media if you like it.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *