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
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
);
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>
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>
<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>
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 }
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 }
There is error in database connection, Please check it in your demo.
ReplyDeletenice example of how you make SQL Injection, by don't validate the user input :)
ReplyDeleteGreat example, very easy to understand. Thanks for the write up.
ReplyDelete@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).
um. two words. "sql injection."
ReplyDeleteyou 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.
All those moaning about SQL validation ... for christ sake ... I suppose you want him to install it on your server too eh?
ReplyDeleteStop 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.
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.
ReplyDeleteum. 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].
ReplyDeleteno -- 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.
@m3mnoch
ReplyDelete"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
Nice tutorial but your code not working. Please test your source code.
ReplyDeletePaul Irish has an excellent jQuery plugin that does just this, as well. You might want to check it out!
ReplyDeletehttp://www.infinite-scroll.com/
the download link broken
ReplyDeletehey
ReplyDeleteIn fire fox browser the code is automatically stopping after few clicks on the more button.
It wasn't easy to implement to my website, because I sort not by id, but by date_added.
ReplyDeleteHowever, I made it!
Thanks, you tutorial is good enough!
Nice thank you*
ReplyDeleteThank's very much !! :D
ReplyDeleteGood thank you, first foray into retrieving through ajax myself and I appreciate your time in giving us a tutorial
ReplyDeletewhy 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
ReplyDeleteHello,
ReplyDeleteI 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.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\voting\loadmore.php on line 87
ReplyDeleteWhy?
Worked perfect, thanks.
ReplyDeleteBTW, I use IPB, so I simply validated the string using intval($this->request['lastmsg']);
:)
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.
ReplyDeleteDo 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?
ReplyDelete@pabloCOOL
ReplyDeleteSoon I will post
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.
ReplyDeleteThis worked great!
ReplyDeleteBUT
What happens if javascript is turned off? Is there an alternative solution to just saying "Turn on JS" ? Thanks...
Great Tutorial! Congratulations!
ReplyDeleteBut when I mix some jqueries at the listing, they stop working @ load more page. Do you have any idea about solving this problem?
Best regards,
Marcelon - Brazil
Can also recommend to take a look at this script - http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/
ReplyDeleteGreat tut's but I try to modify the lit by a table, I need some help please. Thanks
ReplyDeleteThanks 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.
ReplyDeleteThanks for this helpful tutorial. Please how can i load more posts with a time interval.
ReplyDeleteThanks everything works perfectly.
ReplyDeleteThe html produced by ajax_more.php need javascript function in the loadmore.php script. How can I link it to the html produced by ajax_more.php?
thanks for the script, it works great.
ReplyDeletein my loadmore.php i have a php include file there that defines $session->username and i use that in my WHERE statement... i wanted to do the same for ajax_more but it says something about headers being already sent out (something like it starts a new session again). how can i transfer $session->username from loadmore to ajax_more?
How can I integrate this script in this one: http://www.9lessons.info/2011/05/facebook-wall-script-with-php-and.html
ReplyDeleteWhat shall I do?
I have the same error what have people here ! For second loop (press "more" button) it do not get id and not show rest of data ! Please tell how to solve a problem !
ReplyDeleteHow can i integrate in cakephp
ReplyDeletetheres something wrong.. when there are no records to fetch.. it added a more button again.. which shuld be the end...
ReplyDeleteI get error below when there's no more messages:
ReplyDelete"Notice: Undefined variable: msg_id in .../loadmore.php"
Adding:
error_reporting(0);
to the config file helps but ultimately not the answer
Thank you for this script. It works fine.
ReplyDeleteA little problem though, when the results are a set of links, when opening another page and returning back to the results, the results page is re-initialized and doesn't stop on the last clicked position.
thank you alots
ReplyDeleteSOLVED ERROR WHEN CLICKING "more"
ReplyDeleteFILE: ajax_more.php
LINE 13:
$msg_id=$row['ms_gid'];
to : $msg_id=$row['msg_id'];
ENJOY
Habibdev
www.habibdev.net
Hi!
ReplyDeleteThanks for this awesome tut.
I successfully managed to apply this to my php scripts.
It would be really great if you could tell me how to make the content in it crawlable by googlebot. I tried various methods here :- http://code.google.com/web/ajaxcrawling/docs/getting-started.html
but they don't seem to work.
Thanks!!
if you were to use sessions to remember how many was displayed how would you go about it?
ReplyDeleteHello, thank you for the script,
ReplyDeletebut if I want to pass two variables in URL, how do I do?
Here because I must get the ID_comment to choose in the sql table that I must post
Id_comment
a
2
3
4
5
and
id_art = 5
Thank you.
How can i post other variables to the ajax file
ReplyDeleteI am getting this error msg how can i rectify this
ReplyDeleteNotice: Undefined variable: img_id in C:\wamp\www\more results\ajax_more.php on line 21 Call Stack #TimeMemoryFunctionLocation 10.0003681264{main}( )..\ajax_more.php:0 " class="morebox">
wonderfully smart code
ReplyDeletegreat tutorial....
ReplyDeletethanks for the tutorial... it works fine in every browser... no errors in your code...
ReplyDeletehow to prevent the SQL injection for this code?
ReplyDeleteI am beginner in PHP and need your help as I am thinking to use this code in one of my companies running project.
Please suggest and guide me in detail.
Avoiding SQL injection just use mysql_real_escape_string($lastmsg);
ReplyDeleteWill thatbe enough for dangerous SQL injection? If you say so I will do that blindly, as I have got my interest on development by seeing your this website and different codes you have shared here.
ReplyDeleteBut as I see some of the persons in the initial comments has argued on this, that' why I am a bit tensed and curious to know if there is any other steps we can take to prevent our database from getting hacked.
And also I do have a request to you please post some articles on SQL Injection and Session hijacking and moreover on web security in detail.
Now please suggest me whether mysql_real_escape_string($lastmsg); will be enough for preventing SQL Injections.
Thanh you
ReplyDeleteLike the owner said. This is an example of "loading more" not holding your hand on installing a live implementation of code. It's only to show you how to LOAD MORE RESULTs. LMAO! newbie comments.
ReplyDelete(I'm a japanese.)
ReplyDeleteGreat example.
thank you.
I hope to use this in my site.
Thank you Srinivas,
ReplyDeleteis putting "mysql_real_escape_string($lastmsg);" in the code effectively enough to protect the site from sql_injection ?
Have to say that this is a great post and a great find. Have been looking for an easy way to implement something like this on a social networking script that I am making. I don't know much about ajax and this saved my life.
ReplyDeletethis is awesome dude i get your idea it helps me a lot... don't mind them . your concept is awesome!! woho cheers
ReplyDeleteHi THanks you very much ! it work great !
ReplyDeleteI have a question, How do we add more :
$lastmsg=$_POST['lastmsg'];
in ajax_more.php to be able to add more condition in the sql_query like :
$result=mysql_query("select * from activite where id<'$lastmsg' AND POST2='post2' OR POST3='post3' order by id desc limit 5");
THanks you !!!
good example
ReplyDeletehow the data are stored in database?
ReplyDeleteI am not sure if anyone has pointed this out, but there is a small error in the ajax_more.php on line 13
ReplyDeleteLooks like this:
$msg_id=$row['ms_gid'];
should be
$msg_id=$row['msg_id'];
nice
ReplyDeletenice.. dude..
ReplyDeleteI'm getting a double submission issue. Seems like my code is submitting twice. Any ideas?
ReplyDeleteWhen I click Read More Its shows Loading Images Continously
ReplyDeleteDon't know if this was already mentioned, but the .live() method doesn't work with new versions of jQuery. Instead you have to use the .on() method.
ReplyDelete$(document).on(events, selector, data, handler);
Everything else worked great though. Thanks.
When I click Read More Its First time Loading but when click more again ,its not work and the button more transfer to The End !
ReplyDeleteGood job
ReplyDeleteThank you! :)
ReplyDeleteI want to include a facebook like button on every mysql result but it doesn't work. can anyone help me please?
ReplyDeletethank you!
Hey man... In the end you need click the button x2 times to appear 'No more posts'... How i fix this?
ReplyDeleteGreat Code. Thanks!
ReplyDeleteGreat One!
ReplyDeleteFor the newer versions of jquery, changing $(document).live to $(document).on is not enough.
ReplyDeleteIt works the first time, but then it doesn't show further drop-downs.
Any hints?
Thanks
Oh, never mind...
ReplyDelete$(document).on("click",".more",function() [...]
thank you alots
ReplyDeleteHow to work with json w/o using databases
ReplyDeletethanks it's work
ReplyDeleteif you have any trouble with the more button still show eventhough has finish load all here is my fix add
ReplyDeleteif($count>0){
before while in ajax_more.php
at the end
} else{ echo "No More Content to Load"; }
:D
thank u ....this code can load my uploaded images
ReplyDeletehello . guys . i have some trouble with this script . after loads all the messages this notice prompt ""Undefined variable: msg_id in C:\wamp\www\load_more_click\ajax_more.php on line 32 Call Stack #TimeMemoryFunctionLocation 10.0000144240{main}( )..\ajax_more.php:0 " ""
ReplyDeleteanyone please help ? :( BTW , thanks for this script sir Srinivas Tamada.