How to use Codeigniter pagination library together with jQuery and AJAX with complete sourcecode?

I have used Codeigniter's pagination library together with twitter bootstrap(for styling pagination), Handlebars script(to handle html template) and jQuery(to handle dynamic pagination via ajax).
Customized Bootstrap pagination style for Codeigniter pagination library

It will be very easy to understand the following code if you are good at Codeigniter, twitter bootstrap, jQuery and Handlebars script.

Handelbars:Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Click here to read more about what is Handelbars and how it works?

This is working example which I have used in one of my project. If you find any bug, let me know. Or any feedback will be appreciated. I have included Model, View, Controller and jQuery. Hope someone will save a lot of time. You can extend the script the way you want. :)

Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller
{

 function __construct()
 {
  parent::__construct();

 }
 
 function index()
 {
  //load the model
  $this->load->model('your_model');

  $this->load->library('pagination');
  $config = array();
  $config["base_url"] = base_url() . "home/index/";
  $config["total_rows"] = $this->your_model->record_count();
  $config["per_page"] = 10;

  //pagination customization using bootstrap styles
  $config['full_tag_open'] = '<div class="pagination pagination-centered"><ul class="page_test">'; // I added class name 'page_test' to used later for jQuery
  $config['full_tag_close'] = '</ul></div><!--pagination-->';
  $config['first_link'] = '&laquo; First';
  $config['first_tag_open'] = '<li class="prev page">';
  $config['first_tag_close'] = '</li>';

  $config['last_link'] = 'Last &raquo;';
  $config['last_tag_open'] = '<li class="next page">';
  $config['last_tag_close'] = '</li>';

  $config['next_link'] = 'Next &rarr;';
  $config['next_tag_open'] = '<li class="next page">';
  $config['next_tag_close'] = '</li>';

  $config['prev_link'] = '&larr; Previous';
  $config['prev_tag_open'] = '<li class="prev page">';
  $config['prev_tag_close'] = '</li>';

  $config['cur_tag_open'] = '<li class="active"><a href="">';
  $config['cur_tag_close'] = '</a></li>';

  $config['num_tag_open'] = '<li class="page">';
  $config['num_tag_close'] = '</li>';

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

  $data["results"] = $this->your_model->fetch_record($config["per_page"], $page);

//check if ajax is called
if($this->input->post('ajax', FALSE))
{

      echo json_encode(array(
       'results' => $data["results"],
       'pagination' => $this->pagination->create_links()
 ));
}

  //load the view
  $this->load->view('template', $data);

 }

}
Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class your_model extends CI_Model
{

 //set table name to be used by all functions
 var $table = 'tbl_tablename';

 function fetch_record($limit, $start)
 {
  $this->db->limit($limit, $start);
  $query = $this->db->get($this->table);
  return ($query->num_rows() > 0)  ? $query->result() : FALSE;

 }

 function record_count()
 {
  return $this->db->count_all($this->table);
 }

}

View
<html>
<head>
    <title>Codeigniter and dynamic pagination with jQuery and Ajax</title>
 <!-- Le styles -->
 <link href="<?php echo base_url('assets/css/bootstrap.css');?>" rel="stylesheet">
</head>

<body>
    <div id="result_table">
        <script id="result_template" type="text/x-handlebars-template">
         <table class="table table-striped table-bordered">
                   <thead>
                       <tr>
                           <th>Name</th>
                           <th>Age</th>
                            <th>Gender</th>
                                                                 
                       </tr>
                   </thead>   
                     <tbody>
                     
                     <!-- mustache templates -->                                
                    
                     {{! only output if result exists }}
                                                    
                      {{#if results}}
                         {{#each results}}
                          
                         <tr>
                             <td>{{name}}</td>
                             <td>{{age}}</td>
                             <td>{{gender}}</td>                                                                                   
                         </tr>
                         {{/each}}
                     {{else}}
                          <tr><td colspan="3">No records found!</tr></td>
                     {{/if}}
                     </tbody>
                  </table> 
        </script>
    </div>

    <div id="pagination"></div>
<!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="<?php echo base_url('assets/js/jquery.js') ?>"></script>
    
     <script>
     var base_url = "<?php echo base_url(); ?>";
 </script>
    <script src="<?php echo base_url('assets/js/bootstrap.js') ?>"></script>
      <script src="<?php echo base_url('assets/js/handlebars.js') ?>"></script>             
    <script src="<?php echo base_url('assets/js/custom.js') ?>"></script> 
</html>  
jQuery
$(document).ready(function() {

var source = $("#result_table").html();
if (source) {
 
var result_template = Handlebars.compile(source);

 function load_result(index) {
  index = index || 0;
  $.post(base_url + "home/index/" + index, {  ajax: true }, function(data) {
   $("#result_table").html(result_template({results: data.results}));
   // pagination
   $('#pagination').html(data.pagination);
  }, "json");
 }

 //calling the function 
 load_result();
}


 //pagination update
 $('#pagination').on('click', '.page_test a', function(e) {
  e.preventDefault();
  //grab the last paramter from url
  var link = $(this).attr("href").split(/\//g).pop();
  load_result(link);
  return false;
 });
});

Comments

  1. This is also worked for me –
    http://yogeshpatilhere.blogspot.in/2013/11/codeigniter-ajax-pagination-example-code.html

    ReplyDelete
  2. just to point out that the whole thing gets really tricky if you have to use a Joint sql query which pulls data from different tables, then codeigniter pagination active record queries to pull data don´t work.
    and it messes all up ! :-(

    ReplyDelete
    Replies
    1. It depends how you are using join queries to pull datas from different tables. In my case i have join four different tables, and it is working like charm.

      It must be something what is messing your query.

      Good luck.

      Delete
    2. but in this example I don´t see joins anywhere,right? you mean in a different example you may have.
      I will show you my sql query which I can not translate it using CI active records, and basicly there lies the whole issue I think.


      $sql_query = "SELECT adds.*,date_format(date,'%d/%m/%Y') as fdate,
      adds.id as idadd, adsubcat.name as adsubcatname,adcat.name as adcatname
      FROM adds LEFT JOIN (adsubcat,adcat)
      ON ( adds.subcatid=$this->subcatid AND adcat.id=$this->catid AND status='activated')
      WHERE adds.subcatid=adsubcat.id
      ORDER BY adds.id desc";


      $query = $this->db->query($sql_query);

      thanks in advance !

      Delete
    3. Hello Javier,

      I didn't get the clear picture of your tables structure. But I converted your query to
      CI active record. I haven't tested it, but it should work.


      $this->db->select('adds.*, adsubcat.*, adcat.*');
      $this->db->join('adsubcat', 'adds.subcatid = adsubcat.subcatid', 'left');
      $this->db->join('adcat', 'adcat.id = adds.catid', 'left');
      $this->db->where('adds.subcatid', $adsubcatID);
      //get $adsubcatID from somewhere (from controller)
      $this->db->where('adds.status', 'activated');
      $this->db->order_by('adds.id', 'DESC');
      $query = $this->db->get('adds');

      Delete
    4. hi,

      How does this works in when the content with ajax pagination is to loaded only in a part of the page which contains other content?

      Murali

      Delete
  3. Hii, Can anybody comment out Pagination library file which is loaded in this code. please...

    ReplyDelete
  4. I still prefer the old fashion pagination in codeigniter (https://www.cloudways.com/blog/pagination-in-codeigniter/ ) without any magic JS script. Why make the process so difficult when you can do it so quickly?

    ReplyDelete

Post a Comment

Popular Posts