Friday, June 28, 2013

How to get all post data in Codeigniter

Before you have to do this long boring way to get all the post datas using Codeigniter.
$post = array();
foreach ( $_POST as $key => $value )
{
    $post[$key] = $this->input->post($key);
}
var_dump($post); 
Since CI 2.1.0, you can now do the following easy way to get all post data from the form.
$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$data = $this->input->post(); // returns all POST items without XSS filter 
This can be handy if you have dynamically built form with a lot of fields and can't define each field's name. With this method you can get all post data from the form.

Wednesday, June 26, 2013

How To Do Print Screen or Take a Screenshot On a Mac ?

I started to use MAC in my new office and started to enjoy it. This was the best computer I have ever worked. Since I have been using windows for long, I got confused with many keys. I am still learning to be friend with Mac.

Today I needed to print screen, and I couldn't find any button to capture the screen. After googling from some time, I found out the ways to do it.

1. How to take a screenshot on a Mac:


i. Press the Apple key ⌘ + Shift + 3 all at the same time
ii. You will find a capture of the screen on your desktop named ‘Screen Shot ..’
2. Capturing a selected portion of your screen or take a partial screenshot:


i. Press the Apple key ⌘ + Shift + 4 all at the same time
ii. You will see the cursor change to +
iii.Drag a box around the section you want to copy and release the mouse
iv. You will find a capture of the screen on your desktop again entitled ‘Screen Shot..’
3 . Capturing from a selected application window:
i. Press the Apple key ⌘ + Shift + 4 all at the same time
ii. You will see the cursor change to +
iii. Press the spacebar
iv. The cursor will change to a camera. Simply click on the window you want to be captured.
v. Again the capture of the screen will be on your desktop entitled ‘Screen Shot....’
Source: http://www.take-a-screenshot.org/

jQuery fullcalendar integration with PHP and MySQL

This plugin is to create a comprehensive interactive calendar that looks like "Google Calendar". And to perform basic operations on events (display, add, edit) dynamically through AJAX requests, it also allows to easily manipulate the various elements via "drag & drop".
fig: Screen dump of output

Step1 : Download the jQuery fullcalendar plugin by here
You need to grab the required scripts and css. You can find what you need to make it work by looking at default.html file.
The plugin comes with a demo files to test the calendar: the name of the folder is "Demos". Do not hesitate to explore all the files and take a look at the source code of each page to understand the differences.

Step 2 : Create database called 'fullcalendar' and create table called 'evenement'
CREATE TABLE `evenement` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_bin NOT NULL,
  `start` datetime NOT NULL,
  `end` datetime DEFAULT NULL,
  `url` varchar(255) COLLATE utf8_bin NOT NULL,
  `allDay` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT 'false',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=7 ;
Step 3 : Breakdown of required files
You will need following three php files to handle an AJAX request to display, add and edit the events.
1. events.php - We will use the code to connect to a MySql database with PHP and generate a json string for Fullcalendar.
2. add_events.php - We will use the code to add events to the database.
3. update_events.php - We will use the code to update events to the database.
4. default.html - frontend of the calendar. We will perform the ajax requests to make it dynamic calendar.
Step 4 : Complete source code
i. events.php
<?php
// List of events
 $json = array();

 // Query that retrieves events
 $requete = "SELECT * FROM evenement ORDER BY id";

 // connection to the database
 try {
 $bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
 } catch(Exception $e) {
  exit('Unable to connect to database.');
 }
 // Execute the query
 $resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));

 // sending the encoded result to success page
 echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));

?>
ii. add_events.php
// Values received via ajax
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$url = $_POST['url'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}

// insert the records
$sql = "INSERT INTO evenement (title, start, end, url) VALUES (:title, :start, :end, :url)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end,  ':url'=>$url));
?>
iii. update_events.php
<?php

/* Values received via ajax */
$id = $_POST['id'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];

// connection to the database
try {
 $bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
 } catch(Exception $e) {
exit('Unable to connect to database.');
}
 // update the records
$sql = "UPDATE evenement SET title=?, start=?, end=? WHERE id=?";
$q = $bdd->prepare($sql);
$q->execute(array($title,$start,$end,$id));
?>
iv. default.html
<!DOCTYPE html>
<html>
<head>
<link href='css/fullcalendar.css' rel='stylesheet' />
<script src='js/jquery-1.9.1.min.js'></script>
<script src='js/jquery-ui-1.10.2.custom.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<script>

 $(document).ready(function() {
  var date = new Date();
  var d = date.getDate();
  var m = date.getMonth();
  var y = date.getFullYear();

  var calendar = $('#calendar').fullCalendar({
   editable: true,
   header: {
    left: 'prev,next today',
    center: 'title',
    right: 'month,agendaWeek,agendaDay'
   },
   
   events: "http://localhost:8888/fullcalendar/events.php",
   
   // Convert the allDay from string to boolean
   eventRender: function(event, element, view) {
    if (event.allDay === 'true') {
     event.allDay = true;
    } else {
     event.allDay = false;
    }
   },
   selectable: true,
   selectHelper: true,
   select: function(start, end, allDay) {
   var title = prompt('Event Title:');
   var url = prompt('Type Event url, if exits:');
   if (title) {
   var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
   var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
   $.ajax({
   url: 'http://localhost:8888/fullcalendar/add_events.php',
   data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url ,
   type: "POST",
   success: function(json) {
   alert('Added Successfully');
   }
   });
   calendar.fullCalendar('renderEvent',
   {
   title: title,
   start: start,
   end: end,
   allDay: allDay
   },
   true // make the event "stick"
   );
   }
   calendar.fullCalendar('unselect');
   },
   
   editable: true,
   eventDrop: function(event, delta) {
   var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
   var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
   $.ajax({
   url: 'http://localhost:8888/fullcalendar/update_events.php',
   data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
   type: "POST",
   success: function(json) {
    alert("Updated Successfully");
   }
   });
   },
   eventResize: function(event) {
   var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
   var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
   $.ajax({
    url: 'http://localhost:8888/fullcalendar/update_events.php',
    data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
    type: "POST",
    success: function(json) {
     alert("Updated Successfully");
    }
   });

}
   
  });
  
 });

</script>
<style>

 body {
  margin-top: 40px;
  text-align: center;
  font-size: 14px;
  font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;

  }


 #calendar {
  width: 900px;
  margin: 0 auto;
  }

</style>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
How to add delete events?
The below code has not been tested by myself. I have copied it from the comment box. Hopefully it works.
eventClick: function(event) {
var decision = confirm("Do you really want to do that?"); 
if (decision) {
$.ajax({
type: "POST",
url: "your url/delete_events.php",

data: "&id=" + event.id
});
$('#calendar2').fullCalendar('removeEvents', event.id);

} else {
}
}
delete_event.php
$sql = "DELETE from evenement WHERE id=".$id;
$q = $bdd->prepare($sql);
$q->execute();
Ref: http://jamelbaz.com/tutos/integration-de-fullcalendar-avec-php-mysql, http://arshaw.com/fullcalendar/

Thursday, June 20, 2013

Media Queries for Standard Devices

A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color.

I prefer to use the bootstrap media queries responsive standards.


/* Large desktop */
@media (min-width: 1200px) { ... }
 
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
 
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
 
/* Landscape phones and down */
@media (max-width: 480px) { ... }
It depends on the requirement which media query standard to use. You can find many media queries standards and breaking points. This is one example of it.
/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Wednesday, June 19, 2013

How to replace the value of certain key in array using PHP?

Today I needed to replace the value of certain key in array. I do not need to add another key and value. Rather, replace an existing key's value with another value.
Since I am using an associative array and knew the key's name as well. I wrote the following code and it worked.
PHP
$array = array('product' =>'iphone', 'price' =>'4500', 'model'=>'5G');

$array['price'] = '5700'; // say you wanted to change the value of key 'price'

print_r($array);

//outputs : array('product' =>'iphone', 'price' =>'5700', 'model'=>'5G');

If you could want to rebuild the array and keep the element's order, you can use following function.
<?php
function replace_key($find, $replace, $array) {
 $arr = array();
 foreach ($array as $key => $value) {
  if ($key == $find) {
   $arr[$replace] = $value;
  } else {
   $arr[$key] = $value;
  }
 }
 return $arr;
}

//example
$array = array('test' => 0, 'replace this' => 1, 3 => 'hey');
echo '<pre>', print_r($array, true), '</pre>';
$array = replace_key('replace this', 'with this', $array);
echo '<pre>', print_r($array, true), '</pre>';
?>

Monday, June 17, 2013

How to read a value from JSON using PHP?

JSON (JavaScript Object Notation) is a convenient, readable and easy to use data exchange format that is both lightweight and human-readable(like XML, but without the bunch of markup).

If you have a json array and want to read and print its value, you have to use php function
json_decode(string $json, [optional{true, false}]).

If you pass a valid JSON string into the json decode function, you will get an object of type stdClass back. Here's a short example:
<?php
$string = '{"first_name": "Anup", "last_name": "Shakya"}';
$result = json_decode($string);

// Result: stdClass Object ( [first_name] => Anup: [last_name] => Shakya  )
print_r($result);

// Prints "Anup"
echo $result->first_name;

// Prints "Shakya"
echo $result->last_name;
?>

If you want to get an associative array back instead, set the second parameter to true:
<?php
$string = '{"first_name": "Anup", "last_name": "Shakya"}';
$result = json_decode($string, true);

// Result: Array ( [first_name] => Anup: [last_name] => Shakya  )
print_r($result);

// Prints "Anup"
echo $result['first_name'];

// Prints "Shakya"
echo $result['last_name'];
?>

If you want to know more about JSON, here is an official website of JSON.

Friday, June 14, 2013

To format numerical value as swedish currency using PHP

You can use php function money_format() that returns a formatted version of number.
Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
I needed a price to be formatted as Swedish currency. So I need to make my own function which should work. So I came up with this piece of code which converts a numerical string to swedish currency format.

$price = 10000;
echo changeCurrencySwedish($price); //outputs 100,000

function changeCurrencySwedish($price)
{
 $price_array = str_split(strrev($price), 3);
 return strrev(implode(",", $price_array));
}

Show ajax loader image until rendering is finished using Jquery

Add the following html code inside body tag:

<div id="loading">
  <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
</div>

Then add the style class for the div and image to your css:
#loading {
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  position: fixed;
  display: block;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
  text-align: center;
}

#loading-image {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 100;
}

And finally add this jquery to your page inside any function
$(document).ready(function() {
//hide on start
 $('#loading').hide();

//call function
do_something();


 function do_something()
 {
  $("#loading").show();

  var request = $.ajax({
  url: "your_url",
  type: "POST",
  data: {name : "name"},
  dataType: "json"
 });

 request.done(function(msg) {
 $("#loading").hide();
   alert( "Data Saved: " + msg );
});

 request.fail(function(jqXHR, textStatus) {
 $("#loading").hide();
   alert( "Request failed: " + textStatus );
 });
 }

});

Wednesday, June 12, 2013

Generate a TinyURL with PHP

TinyURL allows you to take a long URL like "http://www.developer-paradize.blogspot.com" and turn it into "http://tinyurl.com/n48rbym". Using the PHP and TinyURL API, you can create these tiny URLs on the fly!. Simply provide the URL and you'll received the new, tiny URL in return.

PHP
<?php
//gets the data from a URL
function get_tiny_url($url)  {
$ch = curl_init();
$timeout = 5; 
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//test it out!
$new_url = get_tiny_url('http://www.developer-paradize.blogspot.com/');

//returns http://tinyurl.com/n48rbym
echo $new_url;
?>
If you don't want to use cURL, you can use file_get_contents.
PHP
<?php
function tinyurl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
}
//test it out!
$url = tinyurl('http://www.developer-paradize.blogspot.com/');
//returns http://tinyurl.com/n48rbym
echo $url;
?>

Note: If the server has disabled the file_get_contents() it will create unwanted problem. So I strongly recommend to use cURL() and it will work fine.

Tuesday, June 11, 2013

How to update a JOINed tables using Codeigniter's Active Record?

Codeigniter active record doesn't allow to update a joined tables.
After trying various method and searching the solution, I have found the following solution which does the exactly same thing i.e. update the multiple join tables. By using following method, you can update multiple table using codeigniter active record.
$this->db->set('a.firstname', 'Pekka');
$this->db->set('a.lastname', 'Kuronen');
$this->db->set('b.companyname', 'Suomi Oy');
$this->db->set('b.companyaddress', 'Mannerheimtie 123, Helsinki Suomi');

$this->db->where('a.id', 1);
$this->db->where('a.id = b.id');
$this->db->update('table as a, table2 as b');


Monday, June 10, 2013

jQuery validation : Validate and submit a form without refreshing the page using PHP, jQuery and Bootstrap

The jQuery way of doing form submissions
Here's the jQuery way, which is made possible by AJAX (which stands for Asynchronous JavaScript and XML). AJAX is bascially the technology that makes it possible to exchange data with a server, and update parts of a web page – without reloading the whole page. jQuery includes the necessary functions to implement AJAX into your web application.

In the traditional method, when you click the submit, your browser will load process.php and it will jump from form.php to process.php.

With the jQuery/AJAX way, process.php becomes a background process which the web server will call on, and when you click on the "Submit" button, form.php pushes the data to process.php, but your browser will remain showing form.php. Once the process.php has done what it needs to, it will return to form.php some output to be displayed.

I call the jQuery validate method (make sure you have included the jquery validate plugin - download the script from jqueryvalidation.org) on my form #contact-form, and proceed to define what to validate.

Lastly, the submitHandler is what gets processed if the validation is successful. In this case, I'm doing an ajax post method, sending my form data to process.php, and get back any results as HTML data which will be displayed into #results.

Over at process.php, I'm simply printing out the data received to show you the information was sent and returned.

I have posted the complete source code and screen dump of final outcome. Feel free to use it. :)

Bootstrap Contact form 

Form built with Twitter Bootstrap
<style type="text/css">
label.valid {
width: 24px;
height: 24px;
background: url(../img/valid.png) center center no-repeat;
display: inline-block;
text-indent: -9999px;
}
label.error {
font-weight: bold;
padding: 2px 8px;
margin-top: 2px;
}
</style>
<div class="container-fluid">
<div class="row-fluid">
<div class="span9 offset3">
<form action="" id="contact-form" class="form-horizontal" method="post">
<fieldset>
    <div class="control-group">
        <label class="control-label" for="name">Your Name</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="name" id="name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
<div class="controls">
            <input type="text" class="input-xlarge" name="email" id="email">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <input type="text" class="input-xlarge" name="subject" id="subject">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Your Message</label>
        <div class="controls">
            <textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <button type="submit" class="btn">Send Email</button>
        </div>
    </div>
</fieldset>
</form>
<!-- We will output the results from process.php here -->
<div id="results"></div>
</div>
</div>
</div>

Required jQuery/Javascript
$(document).ready(function() {
 $('#contact-form').validate({
  rules: {
   name: {
    minlength: 2,
    required: true
   },
   email: {
    required: true,
    email: true
   },
   subject: {
    minlength: 2,
    required: true
   },
   message: {
    minlength: 2,
    required: true
   }
  },
  highlight: function(element) {
   $(element).closest('.control-group').removeClass('success').addClass('error');
  },
  success: function(element) {
   element.text('OK!').addClass('valid').closest('.control-group').removeClass('error').addClass('success');
  },
  submitHandler: function(form) {
   // do other stuff for a valid form
   $.post('process.php', $("#contact-form").serialize(), function(data) {
    $("#contact-form").hide();
    $('#results').html(data);
   });
  }
 });
}); // end document.ready

PHP
//process.php
<?php
 print "Form submitted successfully: <br>Your name is <b>".$_POST['name']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>

Ref: http://www.askaboutphp.com/213/php-and-jquery-submit-a-form-without-refreshing-the-page.html

Create a scrolling anchor link with jQuery

Very simply put, this will function like a normal internal anchor link or named anchor link, but will scroll to the specified destination instead of merely jumping there. It’s a really easy-to-implement and awesome thing to add to almost any website.

I’m going to jump right into it.

The HTML
All that is needed for this example is an element to click, and an element to scroll to.

<a id="scroll">Click here to scroll</a>

<img src="images/cat.png" alt="cat" />

I’ve decided to scroll to an image of a random cat, however I think this would be most useful for something like a table of contents.

The jQuery/Javascript
We will be using the click() event, animate effect, scrollTop() manipulation and offset manipulation.

// When the Document Object Model is ready
jQuery(document).ready(function(){
// 'catTopPosition' is the amount of pixels #cat
// is from the top of the document
var catTopPosition = jQuery('#cat').offset().top;

// When #scroll is clicked
jQuery('html, body').animate({scrollTop:catTopPosition}, 'slow');
// Stop the link from acting like a normal anchor link
return false;
});
});

Fairly simple and straight forward jQuery.
Note: jQuery('html, body') is necessary for cross-browser compatibility.
Demo
Source: http://css-plus.com/2010/11/create-a-scrolling-anchor-link-with-jquery/

Friday, June 7, 2013

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