Easy pagination with codeigniter

GFX9.COM share Easy pagination with codeigniter, you can download now.

Tags: , .


In this Tuts+ Premium tutorial we are going to learn how to use CodeIgniter's Pagination Class to paginate our blogs. Once we have firm understanding of how to load, configure and use CodeIgniter's Pagination Class, we'll learn how to use jQuery to make our page navigation dynamic.

We'll examine part of jQuery's AJAX functionality and demonstrate how to use it in conjunction with CodeIgniter's Pagination Class. At the end of this tutorial you should have a solid fundamental understanding of how to paginate data in CodeIgniter using jQuery. You should also be able to implement these techniques into your own CI blog system with ease.


Scroll to the bottom to see the Premium screencast!


Before We Begin...

Before we begin, it's important to point out that we'll be using PHP short open tags throughout this tutorial. You will need to make sure that you have 'short_open_tags' enabled within your php.ini file. Otherwise, you'll need open up your favorite text editor or IDE to find and replace all of the short open tags with full open tags. Also, in conjunction with the short tags, we'll also use the shorthand for 'echo' which is an equal sign.


CodeIgniter - the Initial Setup


There are just a few simple things we need to do in order to get started.

First, we're going to pull our application folder out of our system folder. This isn't required but it is recommended and can make upgrading to a newer version of CodeIgniter a bit simpler.

Next, in our 'application/config' folder, we are going to open up our 'autoload.php' file for editing. We need to autoload our database library (LINE 42) and our 'url' and 'text' helpers (LINE 54).

 
/* 
| ------------------------------------------------------------------- 
|  Auto-load Libraries 
| ------------------------------------------------------------------- 
| These are the classes located in the system/libraries folder 
| or in your system/application/libraries folder. 
| 
| Prototype: 
| 
|	$autoload['libraries'] = array('database', 'session', 'xmlrpc'); 
*/ 
 
$autoload['libraries'] = array('database'); 
 
 
/* 
| ------------------------------------------------------------------- 
|  Auto-load Helper Files 
| ------------------------------------------------------------------- 
| Prototype: 
| 
|	$autoload['helper'] = array('url', 'file'); 
*/ 
 
$autoload['helper'] = array('url', 'text');

Now, in the same folder, let's open up our 'config.php' file. We need to change our 'base_url' for the site. (LINE 14)

 
/* 
|-------------------------------------------------------------------------- 
| Base Site URL 
|-------------------------------------------------------------------------- 
| 
| URL to your CodeIgniter root. Typically this will be your base URL, 
| WITH a trailing slash: 
| 
|	http://example.com/ 
| 
*/ 
$config['base_url']	= "http://localhost/CI_pagination_tut/";

Now, we'll specify our Database connectivity settings in our 'database.php' file (LINES 40-51) located in the same directory.

 
/* 
| ------------------------------------------------------------------- 
| DATABASE CONNECTIVITY SETTINGS 
| ------------------------------------------------------------------- 
| This file will contain the settings needed to access your database. 
| 
| For complete instructions please consult the "Database Connection" 
| page of the User Guide. 
| 
| ------------------------------------------------------------------- 
| EXPLANATION OF VARIABLES 
| ------------------------------------------------------------------- 
| 
|	['hostname'] The hostname of your database server. 
|	['username'] The username used to connect to the database 
|	['password'] The password used to connect to the database 
|	['database'] The name of the database you want to connect to 
|	['dbdriver'] The database type. ie: mysql.  Currently supported: 
			 mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 
|	['dbprefix'] You can add an optional prefix, which will be added 
|				 to the table name when using the  Active Record class 
|	['pconnect'] TRUE/FALSE - Whether to use a persistent connection 
|	['db_debug'] TRUE/FALSE - Whether database errors should be displayed. 
|	['cache_on'] TRUE/FALSE - Enables/disables query caching 
|	['cachedir'] The path to the folder where cache files should be stored 
|	['char_set'] The character set used in communicating with the database 
|	['dbcollat'] The character collation used in communicating with the database 
| 
| The $active_group variable lets you choose which connection group to 
| make active.  By default there is only one group (the "default" group). 
| 
| The $active_record variables lets you determine whether or not to load 
| the active record class 
*/ 
 
$active_group = "default"; 
$active_record = TRUE; 
 
$db['default']['hostname'] = "localhost"; 
$db['default']['username'] = "ci_admin"; 
$db['default']['password'] = "pagination_tut"; 
$db['default']['database'] = "ci_pagination_tut"; 
$db['default']['dbdriver'] = "mysqli"; 
$db['default']['dbprefix'] = ""; 
$db['default']['pconnect'] = TRUE; 
$db['default']['db_debug'] = TRUE; 
$db['default']['cache_on'] = FALSE; 
$db['default']['cachedir'] = ""; 
$db['default']['char_set'] = "utf8"; 
$db['default']['dbcollat'] = "utf8_general_ci";

Finally, we are going to open up our 'routes.php' file and change our 'default_controller' from 'welcome' to 'blogs' (LINE 43). We will be creating our 'blogs' controller shortly.

 
| ------------------------------------------------------------------------- 
| RESERVED ROUTES 
| ------------------------------------------------------------------------- 
| 
| There are two reserved routes: 
| 
|	$route['default_controller'] = 'welcome'; 
| 
| This route indicates which controller class should be loaded if the 
| URI contains no data. In the above example, the "welcome" class 
| would be loaded. 
| 
|	$route['scaffolding_trigger'] = 'scaffolding'; 
| 
| This route lets you set a "secret" word that will trigger the 
| scaffolding feature for added security. Note: Scaffolding must be 
| enabled in the controller in which you intend to use it.   The reserved  
| routes must come before any wildcard or regular expression routes. 
| 
*/ 
 
$route['default_controller'] = "blogs"; 
$route['scaffolding_trigger'] = "";

That's it for our configuration settings! Let's create our database...


Forging Ahead - Creating Our Table in CodeIgniter


We're now going to create a new table for our blogs. This table will have just four rows: 'blog_id', 'title', 'author' and 'body. We'll make 'blog_id' our primary key and set it to auto increment. For this tutorial, we'll be using CodeIgniter's Database Forge Class to do this.

Our first step will be to create a simple controller which will build our table. Open up your application/controllers folder and create a new file named create.php. You'll set up your controller as follows:

 

As you can see we are extending the Controller and have left the Index() function blank for now. We'll first need to load the Database Forge Class within the Index():

 
	function Index() 
	{ 
		$this->load->dbforge() 
	}

Next, we will define our fields within an array and add them to the forge:

 
	function Index() 
	{ 
		$this->load->dbforge(); 
		 
		$fields = array( 
		   'blog_id' => array( 
				'type' => 'INT', 
				'constraint' => 5, 
				'unsigned' => TRUE, 
				'auto_increment' => TRUE 
		   ), 
		   'author' => array( 
				'type' => 'VARCHAR', 
				'constraint' => '50', 
		   ), 
		   'title' => array( 
				'type' =>'VARCHAR', 
				'constraint' => '125', 
		   ), 
		   'body' => array( 
				'type' => 'TEXT', 
				'constraint' => '4000', 
		   ), 
		); 
		 
		$this->dbforge->add_field($fields); 
	}

As you can see we have set our 'blog_id' to auto-increment but we haven't set it as the Primary Key yet.

Now, we need to define the 'blog_id' as our Primary Key.

 
	function Index() 
	{ 
		$this->load->dbforge(); 
		 
		$fields = array( 
		   'blog_id' => array( 
				'type' => 'INT', 
				'constraint' => 5, 
				'unsigned' => TRUE, 
				'auto_increment' => TRUE 
		   ), 
		   'author' => array( 
				'type' => 'VARCHAR', 
				'constraint' => '50', 
		   ), 
		   'title' => array( 
				'type' =>'VARCHAR', 
				'constraint' => '125', 
		   ), 
		   'body' => array( 
				'type' => 'TEXT', 
				'constraint' => '4000', 
		   ), 
		); 
		 
		$this->dbforge->add_field($fields); 
 
		$this->dbforge->add_key('blog_id', TRUE); 
	}

Notice the second parameter of the add_key() function? To set a Primary Key we simply have to specify 'TRUE' in the second param of the add_key() function.

Lastly, we will create our new 'blogs' table:

 
	function Index() 
	{ 
		$this->load->dbforge(); 
		 
		$fields = array( 
		   'blog_id' => array( 
				'type' => 'INT', 
				'constraint' => 5, 
				'unsigned' => TRUE, 
				'auto_increment' => TRUE 
		   ), 
		   'author' => array( 
				'type' => 'VARCHAR', 
				'constraint' => '50', 
		   ), 
		   'title' => array( 
				'type' =>'VARCHAR', 
				'constraint' => '125', 
		   ), 
		   'body' => array( 
				'type' => 'TEXT', 
				'constraint' => '4000', 
		   ), 
		); 
		 
		$this->dbforge->add_field($fields); 
 
		$this->dbforge->add_key('blog_id', TRUE); 
		 
		$this->dbforge->create_table('blogs', TRUE); 
	}

Take note of the second parameter in the create_table() function, it's set to 'TRUE'. This adds an "IF NOT EXISTS" clause into our SQL statement.

To create this new table we simply have to navigate to this controller/function: 'index.php/create/'. Your blogs table should be ready now. You can go ahead and delete this controller if you like as we won't be needing it anymore.


Inserting Sample Data With CodeIgniter's Scaffolding

FOR DEVELOPMENT ONLY


Please note that the CI Scaffolding has been deprecated since version 1.6 but is still in use. Nevertheless, it's a simple and quick way to add or manipulate 'sample' data in your database on the fly.

Loading up the Scaffolding is much like loading a library, model or helper, we extend the controller and then load what it is we need. We'll load up a Scaffolding for our 'blogs' table within our Blogs Controller which we'll create now. Open up your application/controllers folder and create a new file named blogs.php:

 
load->scaffolding('blogs'); 
	} 
}

Next, within our 'routes.php' file (application/config folder - LINE 44) we need to specify a 'secret word' as our scaffolding_trigger.

Navigating to 'index.php/blogs/your_secret_word' will bring up the scaffolding for this table and allow us to create/update/delete records quickly.

 
| ------------------------------------------------------------------------- 
| RESERVED ROUTES 
| ------------------------------------------------------------------------- 
| 
| There are two reserved routes: 
| 
|	$route['default_controller'] = 'welcome'; 
| 
| This route indicates which controller class should be loaded if the 
| URI contains no data. In the above example, the "welcome" class 
| would be loaded. 
| 
|	$route['scaffolding_trigger'] = 'scaffolding'; 
| 
| This route lets you set a "secret" word that will trigger the 
| scaffolding feature for added security. Note: Scaffolding must be 
| enabled in the controller in which you intend to use it.   The reserved  
| routes must come before any wildcard or regular expression routes. 
| 
*/ 
 
$route['default_controller'] = "blogs"; 
$route['scaffolding_trigger'] = "blogCRUD";

Now we can navigate to our Scaffolding


Go ahead and click on 'Create New Record' and add some sample data...


Once we've finished inserting some data, it's very important that we remove our Scaffolding completely. Go back into 'routes.php' (application/config/routes.php - LINE 44) and delete the 'scaffolding_trigger' secret word and then remove the scaffolding init from the 'blogs.php' Controller (application/controllers/blogs.php - LINE 8).


Fetching and Displaying Our Blogs Using CodeIgniter's 'Active Record' Class


CodeIgniter's Active Record Class is excellent. It's chain-able and it's very easy to use. Let's dive right in!

The first thing we'll do here is build our query. We want to display our blog entries in descending order so that the most recent entry is shown first. To do this we will use the 'order_by' method. Let's take a look at our blogs.php Controller and create our Index() function now:

 
db->order_by('blog_id', 'DESC'); 
	} 
}

We are ordering our blogs by their primary key, blog_id, in descending order.

Next, we'll query our database and add our results to the $data array.

 
	function Index() 
	{ 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
	}

Lastly, we'll load our view passing our $data array to it. We will call this view 'blog_index' and create it in just a moment.

 
	function Index() 
	{ 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
 
		$this->load->view('blog_index', $data); 
	}

Creating Our View File


It's time to create our view file. Open up your application/views folder and create a new file named 'blog_index.php'.

You'll notice that I'm loading up jQuery and the jQuery UI here and getting our document ready function prepared as well. This will be used later on.

 
 
 
	 
		 Pagination with Codeigniter and jQuery 
		  
 
		  
		  
 
		  
 
	 
 
	 
	 

Now, let's build a simple HTML structure for our blogs. We'll start with a container for the page, DIV#page.

 
 
 
	 
		 Pagination with Codeigniter and jQuery 
		  
 
		  
		  
 
		  
 
	 
 
	 
	 
	

Now, create a container to hold all of our individual blog entries, DIV#blogContainer. Within it, we'll add a level one header for our blog content.

 
 
 
	 
		 Pagination with Codeigniter and jQuery 
		  
 
		  
		  
 
		  
 
	 
 
	 
	 
	

Sample Blog Index

Now, within DIV#blogContainer, we'll make a container for each individual blog, DIV.blog. Within it, we'll create two header elements for the 'title' and 'author' fields and a paragraph for the 'body' field. After the closing tag for DIV.blog, we'll add a separator by using the HTML hr element.

 
 
 
	 
		 Pagination with Codeigniter and jQuery 
		  
 
		  
		  
 
		  
 
	 
 
	 
	 
	

Sample Blog Index

Author:


It's All in the Loop - Displaying Our Blogs


Using a PHP foreach loop within our view, we'll iterate through our blog results and display them within the HTML structure we just built.

(Note that when using an MVC Framework it's important to use as little PHP code in your view as possible.)

We'll start our foreach loop just before DIV.blog and terminate it immediatly after our horizontal rule. We'll be using the alternate syntax for our foreach loop which is nice because we can use regular HTML between the opening and closing tags. Pretty neat, huh?

 
	 
	 
	

Sample Blog Index

result() as $row):?>

Author:


To review, in the example above, you can see that we are iterating through the results of our database query which are contained within the $blog_query array. We defined this array in our 'blogs.php' Controller:

$data['blog_query'] = $this->db->get('blogs').

Since we've set our 'blogs.php' Controller as the default Controller within our 'routes.php' file (application/config/routes.php - LINE 43), when you navigate to your index you should see all of your blog entries displayed in descending order within the given HTML structure we've just built.


Let's add some style to this page by including a Cascading Style Sheet in the HEAD of our view. We'll call it 'main.css'. Since we've specified our site's 'base_url' in the config.php file (application/config - LINE 14) and we've auto-loaded our 'url' Helper (application/config/config.php - LINE 54), we can use a little shortcut for the path to our CSS file by echoing out our site's base_url.

 
 
 
	 
		 Pagination with Codeigniter and jQuery 
		  
		  
		  
 
		  
		  
 
		  
 
	 
 
	 
	 

Now let's create our stylesheet. We'll add some simple rules to clean up our blog index.

 
#blogContainer 
{ 
	padding: 45px; 
	width: 70%; 
} 
#blogContainer H1 
{ 
	color: #2C2C2C; 
	font: bold 25pt Helvetica; 
	text-align: center; 
	letter-spacing: 4px; 
} 
.blog 
{ 
	margin: 0 0 15px; 
	padding: 15px 25px; 
} 
.blog H2 
{ 
	color: #232323; 
	font: bold 14.9pt Helvetica; 
	letter-spacing: 1px; 
	margin: 0; 
} 
.blog H4 
{ 
	color: #232323; 
	font: bold 9.5pt Helvetica; 
	margin: 4px 0 20px 0px; 
} 
.blog P.body 
{ 
	color: #393939; 
	font: 9.5pt Helvetica; 
}

We now have a nice clean looking index.


More often than not, the blogs listed within an index page will have their body of text truncated down to a static length. This makes the page much more orderly and symmetric. Fortunately, this is very simple to do in CodeIgniter! We can set this up in one easy step:

We've already auto-loaded CodeIgniter's 'text' helper in our autoload.php file (application/config/autoload.php - LINE 54). As a result, we can start using it right away. In our view, we'll limit the charecters in our body of text by calling the 'character_limiter()' method on this particular $row. Let's limit the text to 550 characters.

 

title?>

Author: author?>

body, 550)?>

Here's how our blog index looks now that we've truncated our blogs.



Paginating Our Results Using CodeIgniter's Pagination Class


Now, let's paginate our blog results using CodeIgniter's Pagination class.

Our first step is to load the 'Pagination" Library within the Index() function of our 'blogs.php' Controller:

 
	function Index() 
	{ 
          $this->load->library('pagination'); 
 
          $this->db->order_by('blog_id', 'DESC'); 
          $data['blog_query'] = $this->db->get('blogs'); 
           
          $this->load->view('blog_index', $data);           
	}

With our Pagination Library loaded, we can specify our configuration settings and then initialize the Class. We are going to define three specific settings here. (Note that if you've read through the documentation for the Pagination Class you've seen that there are more config options you can specify here such as opening and closing tags for the links etc...)

First, we must specify the base_url to the content we wish to paginate. As a shortcut, we'll use the url helper and concatenate our base_url with the rest of the string that points to our controller/function for the blog index. We must use the full url to our controller/function including the index.php.

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
 
		$this->load->view('blog_index', $data);           
	}

Our next setting, total_rows, will define how many records we want to get from our database. It will serve as the 'LIMIT' in our 'LIMIT / OFFSET' clause. We'll just use CI's Active Record Class here to count all the blogs within our table:

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
		$config['total_rows'] = $this->db->count_all('blogs'); 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
 
		$this->load->view('blog_index', $data);           
	}

Lastly, we need to specify how many rows to display 'per_page'. For this tutorial, let's just display two results per page:

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
		$config['total_rows'] = $this->db->count_all('blogs'); 
		$config['per_page'] = 2; 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
 
		$this->load->view('blog_index', $data);           
	}

Now that we've built an array of configuration settings, we'll initialize pagination with our $config array:

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
		$config['total_rows'] = $this->db->count_all('blogs'); 
		$config['per_page'] = 2; 
 
		$this->pagination->initialize($config); 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs'); 
 
		$this->load->view('blog_index', $data);           
	}

With pagination initialized we'll need to change our query around a bit by adding a 'LIMIT' and 'OFFSET' clause to it. We'll use the 'total_rows' setting from our $config array for the LIMIT. For the offset, we'll use the third URI segment relative to what page the user is on. So, if we navigate to '/index.php/blogs/index/2', our offset will be 2. Simple, right?

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
		$config['total_rows'] = $this->db->count_all('blogs'); 
		$config['per_page'] = 2; 
 
		$this->pagination->initialize($config); 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs', $config['per_page'], $this->uri->segment(3)); 
 
		$this->load->view('blog_index', $data);           
	}

The last thing we'll need to do here is create our navigation links. CodeIgniter makes this easy. We'll get our links ready by calling the create_links() function adding them to our $data array.

 
	function Index() 
	{ 
		$this->load->library('pagination'); 
		$config['base_url'] = base_url().'index.php/blogs/index/'; 
		$config['total_rows'] = $this->db->count_all('blogs'); 
		$config['per_page'] = 2; 
 
		$this->pagination->initialize($config); 
 
		$this->db->order_by('blog_id', 'DESC'); 
		$data['blog_query'] = $this->db->get('blogs', $config['per_page'], $this->uri->segment(3)); 
		 
		$data['pagination_links'] = $this->pagination->create_links(); 
 
		$this->load->view('blog_index', $data);           
	}

With our pagination_links passed to the view, we just need to display them. Let's create a container for them within DIV#blogContainer. We'll create DIV#pagination and within it echo out our pagination links:

 
	

Sample Blog Index

Author:

It's important that we place DIV#pagination within DIV#blogContainer. When we move on to paginating with jQuery, we'll be loading in DIV#blogContainer dynamically. So, in order to have to correct set of links, per page, we need to be load them in dynamically as well.

Here's how our un-styled pagination links will look:


Let's add a few simple CSS rules for our pagination links in our stylesheet:

 
#pagination 
{ 
	margin: 20px 0 0; 
	padding: 0 15px; 
} 
#pagination>* 
{ 
	font: bold 7.3pt Helvetica; 
	color: #1D1D1D; 
	cursor: pointer; 
	border: 2px solid #4E4E4E; 
	padding: 3px 9px; 
	text-decoration: none; 
} 
#pagination>A 
{ 
	border: 1px solid #919191; 
	padding: 3px 9px; 
	text-decoration: none; 
}

Here's how our pagination links will look with the addition of a few CSS rules:



Using jQuery to Make Our Pagination Dynamic... and Fun.


Now that we've have got CodeIgniter's pagination up and running, we'll use jQuery to make our navigation dynamic.

In order to do this we are going to utilize several of the many great features within the jQuery library.

  • We will be using jQuery selectors to match the DOM elements we'll be working with.
  • We will be using jQuery's live() function to bind handlers to all of the current and future matched elements we specify.
  • We will be using jQuery's Event Object to prevent navigation when clicking on links.
  • We will be using jQuery's animate() function to toggle the opacity of our blogs before and after we load them.
  • We will be using jQuery's AJAX load() function to load in paginated content from their respective pages.
  • Lastly, we'll be using callbacks within some of our functions in order to synchronize what we are doing.

Let's start by using live() to bind a handler for the 'click' event of each current and future pagination link. We, of course, do this within our document ready function.

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
 
		});

Notice that we are adding the argument 'e' to this function. The event object will be passed to this argument when we trigger the 'click' event.

Now, we need to prevent the default action when clicking on these links, which, in this case, would be page navigation. We'll prevent navigation by using our event handler, e, and the preventDefault() method within the event object.

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
 
		});

Now, before we do anything else, we'll cache all of the selectors we'll be using by building an object. It's always a good idea to cache your selectors and the neater your namespace is the better. We'll name our object 'pagination'. It will contain three three items, the container for all of things blog related (DIV#page), the container for all of the individual blog entries (DIV#blogContainer) and the HREF target for the blogs we wish to load. We'll concatenate the HREF attribute of the links with the id of our blog container so as to only GET this container.

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
 
		});

Our next step will be to hide the current content from view by animating it's opacity to 0. We'll set our animation speed to 400 and use a little bit of easing to make it smooth. Additionally, we'll make use of a callback function here. The callback will be executed once the animation is complete:

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
			 
			pagination.content.animate({opacity:0}, 400, "easeInOutCubic", function(){ 
			 
			}); 
 
		});

Now, in our animation callback, we'll use jQuery's AJAX load() to GET our blog container and load it into the page. The nice thing about using load is that it automatically replaces all of the old content with the new. Please note that we are going to use another callback within our load() function as well:

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
			 
			pagination.content.animate({opacity:0}, 400, "easeInOutCubic", function(){ 
			 
				pagination.container.load(pagination.target, function(){ 
				 
				}); 
				 
			}); 
 
		});

To review, we are animating the opacity of our DIV#blogContainer, which contains all of our individual blogs as well as our pagination links, to zero. Then, we use jQuery's AJAX load() function to 'GET' the DIV#blogContainer form the 'target' page we specified earlier.

Next, we must animate the opacity of our content back to one. We'll do this as a callback to our load() function so that the animation begins once the blogs are loaded:

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
			 
			pagination.content.animate({opacity:0}, 400, "easeInOutCubic", function(){ 
			 
				pagination.container.load(pagination.target, function(){ 
				 
					pagination.content.animate({opacity:1}, 400, "easeInOutCubic"); 
					 
				}); 
				 
			}); 
 
		});

We have now jQueryified and AJAXified our blogs! Hold the cheers, though, as an occasion may arise where you have some javascript bound to your dynamic content and you're unable to use jQuery's live() function to handle it. In this case, you'll need to bind your code to a custom event and then trigger that event after loading in the content so as to rebind it. Fortunately, we can use the live() function with custom events.

Creating a custom event is as simple as using the trigger() function to trigger it on it's matched element. So, once the content has been loaded, we'll trigger a new event on our DIV#blogContainer called 'loadComplete'.

 
	$(function(){ 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
			 
			pagination.content.animate({opacity:0}, 400, "easeInOutCubic", function(){ 
			 
				pagination.container.load(pagination.target, function(){ 
				 
					pagination.content.animate({opacity:1}, 400, "easeInOutCubic") 
					.trigger('loadComplete'); 
					 
				}); 
				 
			}); 
 
		});

Now, we can use live() to bind some javascript to the 'loadComplete' event for DIV#blogContainer. Please note that in order to execute this block of code within our document ready function we'll have to trigger it manually the first time. To demonstrate how this works, let's add some jQuery UI Framework classes to our pagination links and some mouseenter / mouseleave behavior as well:

 
	$(function(){ 
	 
		$('#blogContainer').live('loadComplete', function(){	 
			$('#pagination STRONG').addClass('ui-state-active'); 
			$('#pagination A').addClass('ui-state-default'); 
			$('#pagination A.ui-state-default').bind('mouseenter mouseleave', function(e){ 
				 (e.type === 'mouseenter') ? $(this).addClass('ui-state-hover') : $(this).removeClass('ui-state-hover'); 
			}); 
		}).trigger('loadComplete');; 
 
		$('#pagination *').addClass('ui-corner-all');	 
	 
		$("#pagination A").live('click', function(e){ 
			e.preventDefault(); 
			 
			var pagination = { 
				container : $('#page'), 
				content : $('#blogContainer'), 
				target : $(this).attr('href') + ' #blogContainer' 
			} 
			 
			pagination.content.animate({opacity:0}, 400, "easeInOutCubic", function(){ 
			 
				pagination.container.load(pagination.target, function(){ 
				 
					pagination.content.animate({opacity:1}, 400, "easeInOutCubic").trigger('loadComplete'); 
					 
				}); 
				 
			}); 
 
		});

This is worth mentioning... We are binding an addClass() and removeClass() function to the mouseenter and mouseleave events for our links. This deserves an explanation as it's a very useful bit of code...

Using a 'Ternary Operator', we are binding functions to two different events here, 'mouseenter' and 'mouseleave':

(CONDITION) ? returned if true : returned if false;

We use the jQuery event object here to determine if the 'type' of event is 'mouseenter', this is our CONDITION. If the event being triggered is 'mouseenter' we'll add a class. If not, we'll remove a class.

With our code in place now, we'll need to add a UI Framework style sheet to the HEAD of our document. We're going to use the 'south-street' theme for this tut:

 
 
	Pagination with Codeigniter and jQuery 
	 
 
	 
	 
 
	 
	 
 
	 
 

Lastly, we'll need to adjust our stylesheet a bit since we're using the jQuery UI Framework for our links:

 
#pagination>* 
{ 
	cursor: pointer; 
	font: 7.3pt Helvetica; 
	padding: 3px 9px; 
	text-decoration: none; 
} 
#pagination>A 
{ 
	padding: 3px 9px; 
	text-decoration: none; 
}

Let's have a look at our links look now that we've incorporated the jQuery UI Framework:


Go ahead and try it out. You'll see that by using a custom event we are rebinding all of our javascript to the fresh content. It's smooth, simple and fun!


The End


That's it! I hope you've enjoyed this tut and learned something new from it! You should now have a strong understanding of how to use CodeIgniter's Pagination Class and jQuery to paginate your blogs in a fun and dynamic way.





submit to reddit


Similar content