Codeigniter pagination library with jQuery and AJAX

pagination

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).

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

Handlebars: Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.

This is a working example which I have used in one of my projects. If you find any bug, let me know. Or any feedback will be appreciated. I have included Model, View, Controller and jQuery

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;
 });
});

Check This Also

Difference between AngularJS and Angular 2 Make a Mobile app in just 10 minutes With Ionic Framework Angular 9: What to Expect in New Version of Angular Alert (Toaster) Notifications in Angular 8