Twitter-like pagination using CodeIgniter and jQuery

twitter pagination icon Twitter like pagination using CodeIgniter and jQueryIf you use Twitter you'll notice that there is a more button at the bottom at the bottom of your timeline, when you click this more tweets appear. This is Twitters way of paginating a page. In this tutorial I'll show you how to create a pagination system using CodeIgniter and jQuery that is almost identical to Twitters.

First of all copy this SQL into your database to create a table that we will be using to grab rows from.

CREATE TABLE  `tutorials`.`twitter_messages` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) NOT NULL ,
`message` VARCHAR( 140 ) NOT NULL
) ENGINE = INNODB

Create the controller

The class we create is going to be called twitterpagination:

<?php
class twitterpagination extends Controller {
 
}

inside the controller class create a function called index()

function index()
{
	$this->load->helper('url');
	$this->load->model('twitterpagination_model');
	$data['num_messages'] = $this->twitterpagination_model->num_messages();
	$data['latest_messages'] = $this->twitterpagination_model->get_messages();
	$this->load->view('twitterpagination/index', $data);
}

We load the url helper because we will be using base_url() in our view to link to our stylesheet. The model we will be creating is twitterpagination_model so we call this also. $data['num_messages'] returns the number of messages in the database and $data['lastest_messages'] loads the 10 newest rows from the database. Lastly we include a view that we will be creating and pass in $data.

Inside the controller I have created two more functions insert_rows() and get_messages(). The function insert_rows() will insert 50 examples rows for us to retrieve from the table.

function insert_rows()
{
	$this->load->database();
	$i = 0;
	while($i < 50)
	{
		$i++;
		$data = array('username' => 'user', 'message' => 'message ' . $i);
		$this->db->insert('twitter_messages', $data);
		echo $i. '<br />';
	}
}

The last function we have in our controller is get_messages()

function get_messages($offset)
{
	$this->load->model('twitterpagination_model');
	$data['latest_messages'] = $this->twitterpagination_model->get_messages($offset);
	$this->load->view('twitterpagination/get_messages', $data);
}

This function will be called from the view using an ajax call. We have one parameter called $offset, we use this so we know where to pull the next set of rows from in the table. We simply include the twitterpagination_model, call the get_messages() function from the model and pass in the data to the view.

Here is all of the controller code:

<?php
class twitterpagination extends Controller {
 
	function index()
	{
		$this->load->helper('url');
		$this->load->model('twitterpagination_model');
		$data['num_messages'] = $this->twitterpagination_model->num_messages();
		$data['latest_messages'] = $this->twitterpagination_model->get_messages();
		$this->load->view('twitterpagination/index', $data);
	}
 
 
	function insert_rows()
	{
		$this->load->database();
		$i = 0;
		while($i < 50)
		{
			$i++;
			$data = array('username' => 'user', 'message' => 'message ' . $i);
			$this->db->insert('twitter_messages', $data);
			echo $i. '<br />';
		}
	}
 
 
	function get_messages($offset)
	{
		$this->load->model('twitterpagination_model');
		$data['latest_messages'] = $this->twitterpagination_model->get_messages($offset);
		$this->load->view('twitterpagination/get_messages', $data);
	}
 
}

Save this file as twitterpagination.php inside the controllers folder.

The Model

For the model we create a file called twitterpagination_model.php inside the models folder. Then we create a class called twitterpagination_model which extends Model.

<?php
class twitterpagination_model extends Model {
 
}

Next we create the function that will pull the messages from the table.

function get_messages($offset=0)
{
	$this->db->order_by('id', 'desc');
	$query = $this->db->get('twitter_messages', 10, $offset);
	return $query->result();
}

We order the ID descending so that the newest rows are called first. Then we create a variable called $query and retrieve the 10 latest messages from twitter_messages.

Another function that we create in the model is num_messages(). This function returns the number of messages and will be call in the view. This is so we know how many messages are in the table and when to hide the "more" button in the view so the user cannot see it anymore.

function num_messages()
{
	$query = $this->db->count_all_results('twitter_messages');
	return $query;
}

That is all we need to do for the controller.

The View

First of all create a folder called twitterpagination inside the views folder, then create two files called index.php and get_messages.php.

The code for index.php

The most important thing about this file is not to forget to include the jQuery library or the code will not work at all.

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>

Just below the inclusion of the jQuery library we will write our javascript.

<script type="text/javascript">
	$(document).ready(function(){
	var num_messages = <?=$num_messages?>;
	var loaded_messages = 0;
		$("#more_button").click(function(){
			loaded_messages += 10;
			$.get("twitterpagination/get_messages/" + loaded_messages, function(data){
				$("#main_content").append(data);
 
			});
 
			if(loaded_messages >= num_messages - 10)
			{
				$("#more_button").hide();
				//alert('hide');
			}
		})
	})
</script>

After we have checked the DOM is ready we create two variables called num_messages and loaded_messages. The variable num_messages is the total number of messages in the table and loaded_messages will increase by 10 every time 10 more rows are retrieved.

We then have a click event for our more button that will send a request to the get_messages view that we will create.

Then we check if the number of loaded messages is the same as the total number off messages so that we know to hide the more button as there are no more rows to retrieve.

The next thing to do is to include the stylesheet.

<link rel="stylesheet" href="<?=base_url();?>stylesheet/main.css" type="text/css" />

Inside the body we include this html:

<div id="main_content">
<?php
foreach($latest_messages as $message)
{
	echo $message->username . ' - ' . $message->message . '<br />';
}
?>
</div>
<div id="more_button">
more
</div>

The div with the id of main_content is where the messages will be loaded and the div with id of more_button is our button that will be clicked to retrieve more messages.

Here is the full html/javascript of the index.php page.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Twitter Pagination</title>
	<script src="http://www.google.com/jsapi"></script>
	<script type="text/javascript">
	google.load("jquery", "1.3.2");
	</script>
	<script type="text/javascript">
		$(document).ready(function(){
		var num_messages = <?=$num_messages?>;
		var loaded_messages = 0;
			$("#more_button").click(function(){
				loaded_messages += 10;
				$.get("twitterpagination/get_messages/" + loaded_messages, function(data){
					$("#main_content").append(data);
 
				});
 
				if(loaded_messages >= num_messages - 10)
				{
					$("#more_button").hide();
					//alert('hide');
				}
			})
		})
	</script>
	<link rel="stylesheet" href="<?=base_url();?>stylesheet/main.css" type="text/css" />
</head>
<body>
	<div id="main_content">
	<?php
	foreach($latest_messages as $message)
	{
		echo $message->username . ' - ' . $message->message . '<br />';
	}
	?>
	</div>
	<div id="more_button">
	more
	</div>
</body>
</html>

The second view that we create is get_messages.php. This is the page that is called when the more button is clicked.

<?php
	foreach($latest_messages as $message)
	{
		echo $message->username . ' - ' . $message->message . '<br />';
	}
?>

Stylesheet

The very last thing we need to do is create a stylesheet for our page to make it look a little nicer.

Create a folder named stylesheet in the root of the CodeIgniter folder and create a file in it called main.css. The path should be {CI_root}/stylesheet/main.php.

#main_content {
	border: #999 1px solid;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	padding: 5px;
}
 
#more_button {
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	color: #990000;
	text-align: center;
	padding: 5px;
	background-color: #fff;
	background-image: url("http://s.twimg.com/a/1261078355/images/more.gif");
	background-repeat: repeat-x;
	cursor: pointer;
	border: 1px solid #AAA;
}
 
#more_button:hover {
	border:1px solid #bbb;
	text-decoration:none;
	background-position:left -78px;
}

Conclusion

Don't forget to configure your database.php file in the config folder and also inside autoload.php make sure you auto load the database library.

$autoload['libraries'] = array('database');

I hope this tutorial has been of use to you, please feel free to post your thoughts and modifications.

Bookmark and Share
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Ping.fm
  • Tumblr
  • Twitter

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

, , , , ,

2 Responses to Twitter-like pagination using CodeIgniter and jQuery

  1. TiktakNight.com May 29, 2010 at 9:34 pm #

    Good tutorial!!! Thx

  2. Bob July 17, 2010 at 3:26 pm #

    Just what I was looking for :)
    Will try to port it to mootools.
    Cheers

Leave a Reply