Loading Searchbox
9lessons programming blog logo
Tuesday, December 1, 2009

Twitter Style Load More Results with jQuery and Ajax.

24 comments
Twitter and Facebook using very nice technique for loading more tweets and updates, when you click the more button old tweets display on the screen. Long days back I had posted an article same like this but I did some mistakes. So in this tutorial I had coded very simple and understanding way. I hope it's useful take a look this live demo

Twitter Style Load More Results with jQuery and Ajax.

Download Script     Live Demo

Twitter API: Up and Running: Learn How to Build Applications with the Twitter API



First create a database table.
CREATE TABLE messages(
msg_id INT AUTO_INCREMENT PRIMARY KEY,
message TEXT
);

javascript Code
Contains javascipt code. $('.more').live("click",function(){} - more is the class name of anchor more button. Using $(this).attr("id") calling more button last message id field value.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js
"></script>
<script type="text/javascript">
$(function()
{
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');

$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove(); // removing old more button
}
});
}
else
{
$(".morebox").html('The End');// no results
}

return false;
});
});
</script>

loadmore.php
Contains simple PHP code. Displaying results from the messages table in descending order.
<div id='container'>
<ol class="timeline" id="updates">

<?php
include('config.php');
$sql=mysql_query("select * from messages ORDER BY msg_id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<li>
<?php echo $message; ?>
</li>
<?php } ?>
</ol>

//More Button here $msg_id values is a last message id value.
<div id="more<?php echo $msg_id; ?>" class="morebox">
<a href="#" class="more" id="<?php echo $msg_id; ?>">more</a>
</div>

</div&gt;

ajax_more.php
Contains PHP code. Displaying records form the messages table where msg_id < last message id.

<?php
include("config.php");
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$lastmsg=mysql_real_escape_string($lastmsg);
$result=mysql_query("select * from messages where msg_id<'$lastmsg' order by msg_id desc limit 9");
while($row=mysql_fetch_array($result))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>

//More Button here $msg_id values is a last message id value.
<div id="more<?php echo $msg_id; ?>" class="morebox">
<a href="#" id="<?php echo $msg_id; ?>" class="more">more</a>
</div>
<?php
}
?>

CSS Code
*{ margin:0px; padding:0px }
ol.timeline
{
list-style:none
}
ol.timeline li
{
position:relative;
border-bottom:1px #dedede dashed;
padding:8px;
}
.morebox
{
font-weight:bold;
color:#333333;
text-align:center;
border:solid 1px #333333;
padding:8px;
margin-top:8px;
margin-bottom:8px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
.morebox a{ color:#333333; text-decoration:none}
.morebox a:hover{ color:#333333; text-decoration:none}
#container{margin-left:60px; width:580px }
Sponsored Links

Recent Posts

Share this post

Subscribe to my feeds

Subscribe
Comments
24 comments
Elango said...

There is error in database connection, Please check it in your demo.

Anonymous said...

nice example of how you make SQL Injection, by don't validate the user input :)

sharms said...

Great example, very easy to understand. Thanks for the write up.

@Anonymous - obviously if you apply it in production you would need to check that, although most sites I work on use frameworks which take care of that already (ie Symfony).

m3mnoch said...

um. two words. "sql injection."

you might want to shore that up before someone sends along a $_POST['lastmsg'] of "'; drop table messages; select 'whoops' as msg_id where ''='"

you know. just a recommendation.

m3mnoch.

Anonymous said...

All those moaning about SQL validation ... for christ sake ... I suppose you want him to install it on your server too eh?

Stop be so god damn lazy and do a little work yourself. If your so knowledgable about sql injection and security then you will have you own practices that you implement anyway so appreciate the scripts and work this guy has done and be thankful he is sharing. Dont be so rude!

If you dont like then you can always go and code your own from scratch.

Anonymous said...

some smartasses who just finished their first php book i suppose - just like to show off. this is a tutorial for a "load more" feature and he has done it well. he is not required to write down every little basic php validation - that's not what the tutorial is for.

m3mnoch said...

um. except this fairly simplistic tutorial isn't for people like you or me. it's for people who don't know how to do this themselves. and that's probably a decent cross-section with the people who don't have a clue about injection or csrf or [insert any one of dozens of popular attack vectors here].

no -- this tutorial is for noobs.

so when some poor noob copy-pastes this code to their production server and then find they've got a dropped database to show for it, well... he can rightly point at you and say "but that anonymous guy on the internet said this was a good tutorial!"

tutorials should at least contain, if not fully teach best practices. especially in this case where there's just a few characters difference between safe and not safe.

at the very least, you shouldn't post potentially harmful code.

m3mnoch.

Srinivas Tamada said...

@m3mnoch

"The Optimist invents the Airplane. The Pessimist invents the Parachute. The one in between will stay on the ground and talk about the faults of both."

In this tutorial I just given a basic idea about loading more results. If you feel free just post the security code here. It's useful to everybody


Thank you

Designer said...

Nice tutorial but your code not working. Please test your source code.

"Cowboy" Ben Alman said...

Paul Irish has an excellent jQuery plugin that does just this, as well. You might want to check it out!

http://www.infinite-scroll.com/

chandan said...

the download link broken

Anonymous said...

hey

In fire fox browser the code is automatically stopping after few clicks on the more button.

Nikita Sumeiko said...

It wasn't easy to implement to my website, because I sort not by id, but by date_added.
However, I made it!

Thanks, you tutorial is good enough!

Anonymous said...

Nice thank you*

Anonymous said...

Thank's very much !! :D

Mike Watts said...

Good thank you, first foray into retrieving through ajax myself and I appreciate your time in giving us a tutorial

martin said...

why are people always looking for faults on someones code.He wanted to show you how to do it and all the security "thingies" you will have to do it yourself.i love this guy.everything that i was looking for is definitely on this site/blog.thanks

Samet ARAS said...

Hello,

I quite liked this article. For security EzSQL and Token use. Example;

$lastmsg = $db->escape($_POST['lastmsg']);

AND
if(isset($_POST['lastmsg']) AND $_POST['token'] == session_id()){

Finally,

var token = "";

data: "lastquestion="+ID+"&token="+token+"",

Sincerely,
Samet ARAS.

Anonymous said...

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\voting\loadmore.php on line 87

Why?

Anonymous said...

Worked perfect, thanks.

BTW, I use IPB, so I simply validated the string using intval($this->request['lastmsg']);

:)

Metafx said...

Hey Srinivas, this is a good tutorial, I have adapted it to a aspect of my website but I have run into an interesting problem which you may be able to help me with. Basically I load a feed of information via ajax onto a main front page and I use your script within the ajax page to call more posts from another ajax page. However, when I reload the ajax request on the main page to remove the requested posts and just show the original ajax request instead of this behavior it shows only requested posts and the original ajax request called from the main page disappears. When I refresh the ajax one more time it goes back to normal but this is really frustrating because it has to double to actually get back to the main ajax feed.

pabloCOOL said...

Do you know if there is a code similar to this that would make it possible to grab content from an RSS feed instead of a MySQL database?

Srinivas Tamada said...

@pabloCOOL

Soon I will post

Anonymous said...

Thanks for the tutorial! It works fine but when there are no more results, instead of displaying "the end" it just loads another more link. I'm not sure if I did anything wrong because I followed your code step by step and proof-read it many time.

Post a Comment

Orkut | FacebookAbout Me

Subscribe now!Feeds RSS

Subscribe now!Recent Posts

Subscribe now!Categories

Subscribe now!Comments

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Join into my community

Labs ProfileRelease

My ProfileTwitter