Twitter Style Load More Results with jQuery and Ajax.
Wall Script
Follow Me:
Tuesday, December 01, 2009

Twitter Style Load More Results with jQuery and Ajax.

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 }
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


83 comments:

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

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

    ReplyDelete
  3. 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).

    ReplyDelete
  4. 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.

    ReplyDelete
  5. 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.

    ReplyDelete
  6. 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.

    ReplyDelete
  7. 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.

    ReplyDelete
  8. @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

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

    ReplyDelete
  10. 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/

    ReplyDelete
  11. hey

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

    ReplyDelete
  12. 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!

    ReplyDelete
  13. Thank's very much !! :D

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

    ReplyDelete
  15. 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

    ReplyDelete
  16. 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.

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

    Why?

    ReplyDelete
  18. Worked perfect, thanks.

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

    :)

    ReplyDelete
  19. 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.

    ReplyDelete
  20. 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?

    ReplyDelete
  21. 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.

    ReplyDelete
  22. This worked great!

    BUT

    What happens if javascript is turned off? Is there an alternative solution to just saying "Turn on JS" ? Thanks...

    ReplyDelete
  23. Great Tutorial! Congratulations!
    But 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

    ReplyDelete
  24. Can also recommend to take a look at this script - http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/

    ReplyDelete
  25. Great tut's but I try to modify the lit by a table, I need some help please. Thanks

    ReplyDelete
  26. 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.

    ReplyDelete
  27. Thanks for this helpful tutorial. Please how can i load more posts with a time interval.

    ReplyDelete
  28. Thanks everything works perfectly.

    The 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?

    ReplyDelete
  29. thanks for the script, it works great.

    in 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?

    ReplyDelete
  30. How can I integrate this script in this one: http://www.9lessons.info/2011/05/facebook-wall-script-with-php-and.html

    What shall I do?

    ReplyDelete
  31. 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 !

    ReplyDelete
  32. How can i integrate in cakephp

    ReplyDelete
  33. theres something wrong.. when there are no records to fetch.. it added a more button again.. which shuld be the end...

    ReplyDelete
  34. I get error below when there's no more messages:

    "Notice: Undefined variable: msg_id in .../loadmore.php"

    Adding:
    error_reporting(0);

    to the config file helps but ultimately not the answer

    ReplyDelete
  35. Thank you for this script. It works fine.
    A 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.

    ReplyDelete
  36. SOLVED ERROR WHEN CLICKING "more"
    FILE: ajax_more.php
    LINE 13:
    $msg_id=$row['ms_gid'];
    to : $msg_id=$row['msg_id'];

    ENJOY
    Habibdev
    www.habibdev.net

    ReplyDelete
  37. Hi!
    Thanks 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!!

    ReplyDelete
  38. if you were to use sessions to remember how many was displayed how would you go about it?

    ReplyDelete
  39. Hello, thank you for the script,

    but 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.

    ReplyDelete
  40. How can i post other variables to the ajax file

    ReplyDelete
  41. I am getting this error msg how can i rectify this
    Notice: 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">

    ReplyDelete
  42. great tutorial....

    ReplyDelete
  43. thanks for the tutorial... it works fine in every browser... no errors in your code...

    ReplyDelete
  44. how to prevent the SQL injection for this code?
    I 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.

    ReplyDelete
  45. Avoiding SQL injection just use mysql_real_escape_string($lastmsg);

    ReplyDelete
  46. Will 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.

    But 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.

    ReplyDelete
  47. Like 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
  48. (I'm a japanese.)
    Great example.
    thank you.

    I hope to use this in my site.

    ReplyDelete
  49. Thank you Srinivas,
    is putting "mysql_real_escape_string($lastmsg);" in the code effectively enough to protect the site from sql_injection ?

    ReplyDelete
  50. 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.

    ReplyDelete
  51. this is awesome dude i get your idea it helps me a lot... don't mind them . your concept is awesome!! woho cheers

    ReplyDelete
  52. Hi THanks you very much ! it work great !

    I 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 !!!



    ReplyDelete
  53. how the data are stored in database?

    ReplyDelete
  54. I am not sure if anyone has pointed this out, but there is a small error in the ajax_more.php on line 13

    Looks like this:
    $msg_id=$row['ms_gid'];

    should be
    $msg_id=$row['msg_id'];

    ReplyDelete
  55. I'm getting a double submission issue. Seems like my code is submitting twice. Any ideas?

    ReplyDelete
  56. When I click Read More Its shows Loading Images Continously

    ReplyDelete
  57. Don'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.

    $(document).on(events, selector, data, handler);

    Everything else worked great though. Thanks.

    ReplyDelete
  58. 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 !

    ReplyDelete
  59. I want to include a facebook like button on every mysql result but it doesn't work. can anyone help me please?
    thank you!

    ReplyDelete
  60. Hey man... In the end you need click the button x2 times to appear 'No more posts'... How i fix this?

    ReplyDelete
  61. Great Code. Thanks!

    ReplyDelete
  62. For the newer versions of jquery, changing $(document).live to $(document).on is not enough.
    It works the first time, but then it doesn't show further drop-downs.
    Any hints?
    Thanks

    ReplyDelete
  63. Oh, never mind...
    $(document).on("click",".more",function() [...]

    ReplyDelete
  64. thank you alots

    ReplyDelete
  65. How to work with json w/o using databases

    ReplyDelete
  66. thanks it's work

    ReplyDelete
  67. if you have any trouble with the more button still show eventhough has finish load all here is my fix add

    if($count>0){

    before while in ajax_more.php

    at the end
    } else{ echo "No More Content to Load"; }

    :D


    ReplyDelete
  68. thank u ....this code can load my uploaded images

    ReplyDelete
  69. hello . 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 " ""

    anyone please help ? :( BTW , thanks for this script sir Srinivas Tamada.

    ReplyDelete

Make in India