As your website grows, it is no longer practical to display all the data at once on the same page. Moreover, the end user will probably be interested with only part of the content. Also, loading all the content at once might increase the server load or simply a waste of bandwidth. This is where pagination comes into play.
First, I am not too sure how you should call this thing that you are going to learn about but its goal is similar to a usual pagination, That is, to display partial content and to save bandwidth! This article is about how to create a similar stuff to twitter and Facebook’s way of displaying data.
If you have no idea what am talking about, see the screenshot below:
Download Full Sourcode (Twitter + Facebook version ) || Facebook Style Demo | Twitter Style Demo
Hopefully ,i have refreshed your memory .Now let’s get into some coding ..
For the sake of simplicity , i’ll explain only the coding for the Facebook “flavour” only . The codes are basically the same for both, only the css style is changed in the twitter flavour .
CSS Codes
body {
font-family:Arial, 'Helvetica', sans-serif;
color:#000;
font-size:15px;
}
a {
color:#2276BB;
text-decoration:none;
}
* {
margin:0px;
padding:0px
}
ol.row {
list-style:none
}
ol.row li {
position:relative;
border-bottom:1px solid #EEEEEE;
padding:8px;
}
ol.row li:hover {
background-color:#F7F7F7;
}
ol.row li:first-child {
}
#container {
margin-left:60px;
width:580px
}
img {
border : none ;
}
/* The most important below */
#facebook_style {
border:1px solid #D8DFEA;
padding:10px 15px;
background-color:#EDEFF4;
}
#facebook_style a {
color:#3B5998;
cursor:pointer;
text-decoration:none;
font-family:"lucida grande",tahoma,verdana,arial,sans-serif;
font-size:11px;
text-align:left;
}
The jQuery Part
The code below makes an ajax call to fetch more data and display it in a div .The code is self-explanatory. One thing I would like to point out is about:
$('.load_more').live("click",function() {
Maybe you are asking yourself why not simply:
$('.load_more').click(function() {
If you try the second one , you will be able to load the data only once after your first click .No more data will be loaded after that . The .live method is an event delegation mechanism that allows you to manipulate the DOM .
$(function() {//When the dom is ready
$('.load_more').live("click",function() { //When user clicks
var last_msg_id = $(this).attr("id");//Get the id from the hyperlink
if(last_msg_id!='end'){ //if not all post has been loaded yet
$.ajax({//fetch the article via ajax
type:] "POST",
url: "facebook_style_ajax_more.php",//calling this page
data: "lastmsg="+ last_msg_id,
beforeSend: function() { // add the loadng image
$('a.load_more').append('<img src="facebook_style_loader.gif" />');
},
success: function(html){
$(".facebook_style").remove();//remove the div with class name "facebook_style"
$("ol#updates").append(html);//output the server response into ol#updates
}
});
}
return false;
});
});
The Body Section
<div id='container'>
<ol id="updates">
<?php
$query ="select * from twitter ORDER BY msg_id ASC LIMIT 9";
$result = mysqli_query($dbc,$query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<li> <?php echo $message; ?> </li>
<?php } ?>
</ol>
<div id="facebook_style">
<a id="<?php echo $msg_id; ?>" href="#" >Show Older Posts <img src="arrow1.png" /> </a>
</div>
</div>
Page being called via Ajax : facebook_style_ajax_more.php
include('database_connection.php');
if(isset($_POST['lastmsg']) &&is_numeric($_POST['lastmsg']))//some validation to prevent sql injection
{
$lastmsg=$_POST['lastmsg']; //getting the row id of last msg displayed
$query="select * from twitter where msg_id>'$lastmsg' order by msg_id asc limit 9";
$result = mysqli_query($dbc,$query);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<li> <?php echo $message; ?> </li>
<?php
}
?>
<?php
if( mysqli_num_rows($result)==9){ //this if else statement "decides" whether end of page has reached or there's more data to load .
?>
<div id="facebook_style"> <a id="<?php echo $message; ?>" href="#" >Show Older Posts <img src="arrow1.png" /></a> </div>
<?php
}else {
echo ' <div id="facebook_style">
<a id="end" href="#" >No More Posts</a>
</div>';
}
}
Credits
The animated loading images were generated from here and there And part of the CSS was taken directly from facebook and twitter’s page source code :) .
Summary
As you can see , it is fairly simple to implement . Honestly , i could not find a reason why you should use this type of pagination instead of the usual one .I think it’s just a question of preference .One way you could improve it is by instead of loading more data when the user clicks ,make it load when the user is scrolling down using Jquery’s .scroll .If you have any suggestion , critics drop me a comment below . That’s what it is used for :) .
Related Posts
- Facebook and Google Plus style of introducing new features using jQuery
- Create a facebook post to wall system using PHP and jQuery Part 2
- Create a facebook post to wall system using PHP and jQuery Part 1
- Username Availability Check in Registration Form using Jquery/PHP
- Creating a Fancy Search Feature with PHP,Mysql and Jquery


{ 4 trackbacks }
{ 33 comments… read them below or add one }
Really nice effect and explaining of how to achieve it.
Excellent post!
I need to do one change in this script, so I need your help.
Presently, when I click ‘Show older posts’, the new posts are displayed just below the previous posts (and hence, the earlier posts are retained!). I want that on clicking ‘Show older posts’, the earlier posts must be removed and only new posts should be displayed.
What changes shall I do to??
replace this code :
$("ol#updates").append(html);with
$("ol#updates").replaceWith ('<ol class="row" id="updates">'+html+'</ol>');The difference between these two line of codes is that , instead of appending the data to the previous one , it replaces it ! Thats all . :)
This is awesome script and cool effort by you . i like this site very much and i shared this site to my friends too. although we are starting learners .
by fate this script not working for me ..
can any one help me ..?
i did exactly what is present on the site ..but it displays only first 9 records ..;-( .in my database there are more than 30 records. when i click more it shows ‘no more posts’ .. what can i do .. plz any one contact me at
kakanivenkatesh@live.com
please help me …
Superb!
But when I’m using this sort of replacement, it directly implies that I must also use a mechanism to view previous posts also! Hence a link for previous page is also required!
So like ‘Show older posts’, a similar link ‘Show newer posts’ or ‘Show recent posts’ needs to be included, that can show the earlier posts.
I hope I’m well able to explain my problem :)
So now what modifications for this??
Add another hyperlink for “show previous post”, and Add
Now everytime you click on “Show more post” hyperlink , the Id will be 18,27,36 etc
But for the Hyperlink “show previous post” ,the id will be generated 36,27,18 ( Backward ) that will cause the previous 9 rows of data to be fetched .In my opinion,i don’t think it will be practical to add a “Show Previous Post” to this type of Pagination . I’m sure what you are looking is this one :
http://tutorialzine.com/2010/05/sweet-pages-a-jquery-pagination-solution/
Though the display and the way in which pages flip in the pagination you recommended is highly desirable, still I cannot use that because its actually based on division of div’s, and not fetching data from database upon user click!!
My project is designing a website like ‘question&answers’, or typically like a forum, which needs to show a set of questions (or just titles) on a page, and then show next set of titles when user clicks ‘Page 2′ or ‘Next Page’, without reloading the whole page. And that is what the tutorial that you have explained above actually does!
And regarding adding “shoe previous post” hyperlink, this doesn’t work! :(
Im busy with my work right now . i can write an example for you but not before monday Asoj ..just to give you some ideas , you need to make changes that the sql query looks like this :
First Page load :
1st click on hyperlink “next ” :
2nd click on Hyperlink “Next” :
1st click on Hyperlink “Previous” :
2st click on Hyperlink “Previous”
Thank you so much Hyder for your ideas.. I’ll be waiting for your example, but if I could make it, I’ll notify you.. But please dont forget to write the code as soon as you get free..
Thanks!
And in this code, instead of $message-9, trying with the double value (i.e. $message-18) worked! and it worked well till the second last page! On the last page, it got confused with itself as there were not exactly 9 posts on the last page.. and screwed up all.. :(
I hope this might give you some more ideas when u’ll try it!
Hello Hyder.
Did you get some to time working on the code? I’ve tried a lot but not getting the exact touch of what to get.. please help!
Hello.
Which do I use in the “show older posts” link? face_book_style_ajax_more.php or facebook_style_pagination? With the first nothing appears and the second gives me
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\wamp\www\gisttest\facebook_style_pagination.php on line 78
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\gisttest\facebook_style_pagination.php on line 79
very nice thanks for sharing..
I implemented your code for one of my sites it works great on FF but not on IE.
I have to refresh the page for it work.
The issue:
user loads page -> hits “More” -> Gets taken to the top of page no new results are shown -> if user hits refresh (very unlikely) it will give the additional results it will not take them to the top of page
@Cesar : which version of IE are you using ?
Thanks for sharing.. It’s very nice tutorial and I’ve been looking for to my personal website. :)
keep good work ^.^
Regards,
Guruh
Is it possible to execute jquery code on recenlty unhidden li’s?
@Alex : i haven’t understood what you really mean but I guess it should be possible :)
Excellent, thanks for sharing! I wanted to use this for search results and need to add variables in my query. I can use $_GET for the first page, but am not sure how to retain and include those variables in the query on the ‘ajax_more’ page. Any suggestions would be greatly appreciated.
Hi Hyder, thanx for the sharing. I understand your code but have one question. What about if my posts are not ordered by the ID but instead, let’s say, it’s a ranking system so the posts will be ordered by the amount of votes they receive. How would you change your code to make it work in this scenario? Thank you very much!
Hi again. I got a solution for my last question about using your code in an ordered-by-ranking posting system. What I did was send through ajax data an internal counter that tracks the ranking position of each post, then, in the php file called in the ajax url, I just did a MySQL SELECT with LIMIT $counter, 10 ($counter has the ranking position of the last post displayed and 10 is the amount of posts I want to show each time).
That was my solution ^^
If you have a better idea please let me know
Hello, There is a error in facebook_style_ajax_more.php of source code facebook.
The error is the next:
in div:
<a id="” href=”#” class=”load_more” >Show Older Posts
is wrong/bad, sorry for my english :(.
There is change to code:
<a id="” for <a id="” for that working fine.
The code working fine is:
<a id="” href=”#” class=”load_more” >Show Older Posts
Thank you for this code.
Kind regards
Not show the code: the comment blog.
Change in line 28 of facebook_style_ajax_more.php:
$message
by
$msg_id
With this change working fine.
Kind Regards
Thx, I was about to post the same. :)
I made it to work separate from a Wordpress. Now my achievement wold be to make it work for Wordpress comments.
Hi Hyder, and thanks a lot for sharing your code, works fine for me…
I just have a small question:
how can I execute $(“ol#updates”).append(html); with a fadeIn or scrolldown??
I mean when you click the button “More” the new content is shown using an animation or fadeIn
thanks a lot
nice tutorial thanks .. would be perfect if you include the database structure aswell
more power and keep the tutorial post coming !
Thank you, it works very well!
Any chance that you or someone else could post the code with this Jquery’s .scroll option you refer to in your summary?
Fantastic … congratulations by the code
Would you mind having this as a plugin for wordpress?
@Neo : I’m no wordpress plug in expert :) I might try create one some day !
Thanks for sharing it’s exactly which I am looking for… great work.
it’s wonderful!
I like it….
i did exactly what you present ..but things gone wrong .
by clicking more button ,it not displaying the data records…
i changed sql and tried but no use .. can any one help me .i’m hopeless
my email id is
kakanivenkatesh@live.com