Monday, January 18, 2016

Ajax Pagination in CodeIgniter Framework

CodeIgniter have the pagination library by default. But many times we are needed to implement the ajax based pagination in CodeIgniter. Because ajax pagination provides better user experience. Today we will discuss how to create ajax pagination in CodeIgniter framework.
At first we need to add ajax pagination into the CodeIgniter Pagination library. Copy the CodeIgniter system pagination library and modify with ajax pagination code. Rename the Pagination class to Ajax_pagination and insert the Ajax_pagination.php file into the libraries folder. You can download the CodeIgniter Ajax Pagination library from here – Ajax_pagination.php.
In this tutorial we will display the list of posts data from the database. Also display the pagination links and implement the ajax pagination for link pages. Please follow the step by step instruction given below.
The folder and files structure look like the below.
  • application
    • controllers
      • posts.php
    • libraries
      • Ajax_pagination.php
    • models
      • post.php
    • views
      • posts
        • index.php
        • ajax-pagination-data.php

Posts table creation:

posts table SQL is like below.
CREATE TABLE `posts` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `content` text 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;

Controller:

Create a controller file named posts.php with Posts class. Into the __construct() function we need to load postmodel, Ajax_pagination library. Also we will the set the per page data limit into $this->perPage variable.
index() function is used to display the posts listing page.
ajaxPaginationData() function is used to load the posts data, requested by the ajax.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');/**
 * Posts Management class created by CodexWorld
 */class Posts extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('post');
        $this->load->library('Ajax_pagination');
        $this->perPage 1;
    }
    
    public function index()
    {
        $data = array();
        
        //total rows count
        $totalRec count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'//parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/index'$data);
    }
    
    function ajaxPaginationData()
    {
        $page $this->input->post('page');
        if(!$page){
            $offset 0;
        }else{
            $offset $page;
        }
        
        //total rows count
        $totalRec count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'//parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('start'=>$offset,'limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/ajax-pagination-data'$datafalse);
    }
}

Model:

Create a model file named post.php with Post class. Into the __construct() function we have defined the table name with $this->postTable variable.
getRows() function return the posts data from the database.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Model{
    
    function __construct() {
        $this->postTable 'posts';
    }
    
    function getRows($params = array())
    {
        $this->db->select('*');
        $this->db->from($this->postTable);
        $this->db->order_by('created','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();
        
        return ($query->num_rows() > 0)?$query->result_array():FALSE;
    }
}?>

View:

We will create 2 view files.
index.php file is used for display the post listing page view and ajax-pagination-data.php file display the post listing view requested by ajax.
$this->ajax_pagination->create_links(); is used to display the ajax pagination links.
index.php
<h1>Posts</h1>
<div id="container">
    <ul class="list" id="postList">
        <?php if(!empty($posts)): foreach($posts as $post): ?>
        <li>
            <p><b>Title:</b>&nbsp;<?php echo $post['title']?></p>
            <p><b>Content:</b>&nbsp;<?php echo $post['content']?></p>
            <p><b>Created:</b>&nbsp;<?php echo $post['created']?></p>
        </li>
        <?php endforeach; else: ?>
        <li class="err_msg">Post(s) not available.</li>
        <?php endif; ?>
        <?php echo $this->ajax_pagination->create_links(); ?>
    </ul>
</div>
ajax-pagination-data.php
<?php if(!empty($posts)): foreach($posts as $post): ?>
<li>
    <p><b>Title:</b>&nbsp;<?php echo $post['title']?></p>
    <p><b>Content:</b>&nbsp;<?php echo $post['content']?></p>
    <p><b>Created:</b>&nbsp;<?php echo $post['created']?></p>
</li>
<?php endforeach; else: ?>
<li class="err_msg">Post(s) not available.</li>
<?php endif; ?>
<?php echo $this->ajax_pagination->create_links(); ?>
 Don’t forget to include the jQuery library into view. Just insert the following code into the view file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Note: This article is taken from : http://www.codexworld.com/ajax-pagination-in-codeigniter-framework/

No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...