Load Data while Scrolling Page Down with jQuery and PHP
Wall Script
Wall Script
Monday, July 20, 2009

Load Data while Scrolling Page Down with jQuery and PHP

This tutorial about my favorite place Dzone like data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website. Take a look at live demo and scroll down.


Load Data while Scrolling Page Down with jQuery and  PHP

Download Script     Live Demo

Database Table
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);

Browser Capability : Safari, Firefox, IE, Chrome



load_data.php
When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")

<?php

include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];

if($action <> "get")
{
?>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,

function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};

$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}

else
{
include('load_second.php'); //include load_second.php
}
?>

load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box"
<?php echo $msg; ?>
</div> 
<?php
} 
?>

load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.

<?php

$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg']; 
?>
<div id="<?php echo $msgID; ?>" class="message_box"
<?php echo $msg;
?>

</div>
<?php
} 
?>

CSS
body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}

ASP Version tutorial : webresourcesdepot.com
web notification

131 comments:

  1. and as of 07/2009 jquery is up to version 1.3.2

    ReplyDelete
  2. It's working with jquery 1.3.2 also...

    ReplyDelete
  3. I wish you included a real javascript version (not with jQuery) so we can implement this with a few lines of proper javascript without having to load the entire jQuery framework.
    That's what's frustrating with jQuery, it's that nobody is writing custom javascript code anymore!...

    ReplyDelete
  4. This works great thanks...

    I had a quite the dilemma. I was loading a rather large user list into a facebox modal window. It was taking about 6 seconds to display the entire list. At first I thought I'd just paginate the list, but things got real complex quick.

    So I adopted your code above to my facebox and it works great.

    Thanks for saving me a good amount of time.

    For those of you interested in using this one a scrollable DIV instead of a window try using this code for scroll function:

    $('div.content').scroll(function(){
    if ($('div.content').scrollTop() + $('div#facebox').height() >= $('div.content').height()) {
    last_msg_funtion();
    }
    });

    ReplyDelete
  5. I will invite you to Ghana. Next Year.
    Ebow Ansah

    ReplyDelete
  6. it doesn't work unless you scroll slowsly. I tried your demo in IE and firefox to confirm. The reason is, it would pass the same id twice, if second scroll event occurs, while secondload.php is still fetching data.

    ReplyDelete
  7. Hello!

    After many test, This script is fine but not scalable. I meet bug everywhere and for all browser when i try to mix it with some jquery or put the script inside js file.

    It return this error code :
    -- Chrome :
    Uncaught TypeError: Object function (D,E){return new n.fn.init(D,E)} has no method 'setInterval' ---

    ---IE8 :
    Détails de l’erreur de la page Web

    Agent utilisateur : Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; InfoPath.2; .NET CLR 3.0.30729)
    Horodateur : Thu, 4 Feb 2010 21:38:11 UTC


    This object don't support this http://.../livehome.js

    ReplyDelete
  8. how can i make it cycle through a given string of id's like "[2,21,114,3]" instead of adding on the previous hit?

    ReplyDelete
  9. Hey I want my webpage load like flickriver.com
    i am not getting any script.

    even I tried this script but it is not working, can anybody tell me how to implement it.
    if live chat possible, it would be great.

    id:- [email protected]

    thanks

    ReplyDelete
  10. nice article, but anybody knows how to do it in asp.net.
    thanks

    ReplyDelete
  11. finally i found it.
    Thanks for the code.

    it really helped. :D

    ReplyDelete
  12. great piece of code man...you did good. But have you figured a solution to the double and sometimes triple load? If you scroll too fast, it will load the data twice and sometimes thrice...

    check it out http://www.afrikaspeaks.com

    ReplyDelete
  13. Hey...just wanted to let you know that I fixed the repetitive data display. It had to do with the loader. Make sure that it's set outside the main content area. eg

    if your content is 600px. set your load_msg_loader to say 700px and a negative top margin of say -100px and aligned to right! this solved mine for me. You can see it at work on my news portal www.afrikaspeaks.com

    Thanx man

    ReplyDelete
  14. Just what I needed. Thank you very much for posting this!

    ReplyDelete
  15. very helpfull, thx for sharing

    ReplyDelete
  16. Thanks a lot for sharing knowledge

    ReplyDelete
  17. Hey, thanks very much for sharing this piece of code. I've modified it a bit to fit my video blogging site, and it really ads a useful effect. I still have a little trouble with double results if scrolling down too fast, but it's not serious.

    Best!
    Dan

    ReplyDelete
  18. repetitive data-issue:
    you could also do something like setting a variable if there is content to load. while this is true, the last_msg_funtion() will not be called. if the feedback comes, you set it back:
    if (data != "") {
    $(".message_box:last").after(data);
    // here you set the loadData variable to false
    }
    i've done something like that here http://deschavü.ch/dejavu, and tested it on firefox3.6, Safari4, Opera(quiteNew), ie7 and ie8. it worked in all these browsers, but in firefox, when you reload the page and you're on the bottom of all entries.
    THX for the code BTW$$$

    ReplyDelete
  19. hello, how if I want to get new records from database for every 10 seconds? The conflict between the two features below :
    1) feature of reload page for every 10 seconds to get new records.
    2) feature of get older records when user scroll down to the page.

    Because both features above are depend on the same variable $last_msg_id, how can I solve the conflict between the two features?

    ReplyDelete
  20. thank u it works :)

    ReplyDelete
  21. Hi Sri,
    This is a great tutorial.
    I tried this for my application.
    But the problem come, when user scroll down very fast.It loads the data multiple time....

    Any idea how can we overcome from this issue.
    Thanks,
    Gaurish

    ReplyDelete
  22. Hi, how to create similar function which loads data by clicking "Load More" button instead of scrolling down? I want to implement at http://www.livepage.info Thank you!

    ReplyDelete
  23. @Livepage

    Try this http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html

    ReplyDelete
  24. Cant fix double load.

    PLease help

    ReplyDelete
  25. thank you very much

    ReplyDelete
  26. U did great.Can i reload the content in particular div instead of whole document??? Please help me!

    ReplyDelete
  27. how to fix this double load problem . maximum times it loads three four times the second page contents.please tell if anyone has solved this problem

    ReplyDelete
  28. Set a variable to prevent it from being called. Some of the names are changed slightly in my example, but this fixes it:



    var bSuppressScroll = false;

    $(document).ready(
    function()
    {
    function last_msg_funtion()
    {
    var ID=$(".search-result-list-element:last").attr("id");
    $('div#loading').show();
    $.post($('div#next_message_location').html() + "?p=" + ID,

    function( data )
    {
    if (data != "")
    {
    $(".search-result-list-element:last").after(data);
    window.bSuppressScroll = false;
    }

    $('div#last_msg_loader').empty();
    $('div#loading').hide();
    } );
    };

    $(window).scroll(function(){
    if ( ( $(window).scrollTop() == $(document).height() - $(window).height() ) && window.bSuppressScroll == false ){
    last_msg_funtion();
    window.bSuppressScroll = true;
    }
    });
    });

    ReplyDelete
  29. Excelente site, ótimo conteúdo...

    ReplyDelete
  30. The script aint working in IE, not your demo either.

    ReplyDelete
  31. thanks, helped me a lot,, very very good,

    ReplyDelete
  32. Thank you Mark Lane !
    That worked for me. No more double posts.

    ReplyDelete
  33. This seems to be almost exactly what I need to make my site actually function! I'm so close, I can taste it! Right now I have a site using the Wordpress eCommerce Plugin (getshopped.org) to sell prints. There ultimately needs to be ~7000 products on a single page and as you might imagine the page takes AGES to load as it is right now with only 3000 products on the page. How would I implement this into my WPEC products page so I can actually make my site usable instead of the bloated Frankenstein of a page that it is right now?

    ReplyDelete
  34. this code is nice but if can fix the issue
    the issue is

    the show more function u have created is called when user scroll down. but if i already loaded the maximum results then the loader should not load, this may create confusion to user that there may be still more data to be loaded.
    what do u say.

    ReplyDelete
  35. i got an error "Could not connect database"..please help how to fix this..

    ReplyDelete
  36. it works but on top of all i get these 2 errors:

    Notice: Undefined index: last_msg_id in /opt/lampp/htdocs/reg/load_data.php on line 5

    Notice: Undefined index: action in /opt/lampp/htdocs/reg/load_data.php on line 6

    ReplyDelete
  37. This is possible in blogspot?

    ReplyDelete
  38. multiple fetches occur
    ps on ie it always fetches3 time

    ReplyDelete
  39. I have problem with Internet Explore, Rows duplicate....

    ReplyDelete
  40. Hi I am working inside an overflow div.In which i used an internal scroll-er with fix height and width of that div container now i want to use the auto load on that container scroll down.

    ReplyDelete
  41. what if in

    $last_msg_id=$_GET['last_msg_id'];
    $action=$_GET['action'];

    if($action <> "get")
    {


    $last_msg_id and $action are not set :(

    ReplyDelete
  42. Use This To Avoid Error Reporting

    "get")
    {
    ?>

    ReplyDelete
  43. I used this code successfully but I have a small problem with data formatting.

    I have around 2000+ rows of data each row contains 5 columns. I used this code and first time I ma loading 50 rows of data and then each time load_second.php page is called and 50 rows of data are getting populated on the webpage.

    I am using table structure to format those data. No my problem is that when load_second.php page's data are getting populated on webpage it foes top of the load_first.php page's data which already loaded on webpage.

    Live site : http://agriculture-caluniv.in/load_data.php

    Can you guys please let me know a solid solution to this problem?
    Ideally the load_second.php page's data should get loaded just below the load_first.php page's data.

    Thanks in advance.

    Soumya Roy

    ReplyDelete
  44. Pls help...

    im trying to retrieve data from many tables (joining) at the same time, but when i scroll down fast it load twice the same data...

    any advice pls

    ReplyDelete
  45. ruizewin please follow on mark lane script..it solved the problem...regards

    ReplyDelete
  46. Thank you for a great article and useful tips, guys!

    ReplyDelete
  47. This is super useful, thanks! I've seen this data load trick used before and was always wondering how it's done.

    ReplyDelete
  48. After using the following java script I get the an error: "Unterminated string constant"


    var bSuppressScroll = false;
    $(document).ready(
    function()
    {
    function last_msg_funtion()
    {
    var ID=$(".search-result-list-
    element:last").attr("id");
    $('div#loading').show();
    $.post
    ($('div#next_message_location').html() +
    "?p=" + ID,
    function( data )
    {
    if (data != "")
    {
    $(".search-result-list-element:last").after
    (data);
    window.bSuppressScroll = false;
    }
    $('div#last_msg_loader').empty();
    $('div#loading').hide();
    } );
    };
    $(window).scroll(function(){
    if ( ( $(window).scrollTop() ==
    $(document).height() - $(window).height
    () ) && window.bSuppressScroll ==
    false ){
    last_msg_funtion();
    window.bSuppressScroll = true;
    }
    });
    });

    ReplyDelete
  49. I am getting the below 2 errors how to solve that?
    ( ! ) Notice: Undefined index: last_msg_id in C:\wamp\www\try\scroll_data.php on line 5

    ( ! ) Notice: Undefined index: action in C:\wamp\www\try\scroll_data.php on line 6

    ReplyDelete
  50. @Srinivas sir : Sir i m not able to get through the above problem. I have tried using isset function but the load_second.php is called only once i.e even the scroll function is not working in my code. Can u plzzzzzzzzzzzzz help me out.

    ReplyDelete
  51. very nice tutorial dude , thank you very much for this tutorial

    ReplyDelete
  52. This is not working in Firefox for me. If I comment the following condition, it works:
    if($(window).scrollTop() == $(document).height() - $(window).height())

    Also when I put any alert within any funtion, whole screen goes blank when scrolled.

    ReplyDelete
  53. It's working on internet explorer 8 while its not working on google chrome :)
    can anyone help on how can i make the code running on google chrome

    ReplyDelete
  54. when i tried this code, i getting the error like
    " Undefined index: last_msg_id in load_data.php and Undefined index: action in load_data.php"
    anyone pls give me solution.
    thnku

    ReplyDelete
  55. Hi

    some issue in IE, the event is triggering two times, any idea ?

    Thanks
    Prajoh

    ReplyDelete
  56. Hi Srinivas, my English is very bad.
    Iam Brazilian lady.
    This code is very good, I'm just having difficulty getting back into a DIV, because I try to leave those windows like Twitter, but the contents from the mysql.
    How could I do? gives you a light?
    I hope your answer.
    Bye

    ReplyDelete
  57. some above code is not working in Mozilla, this could be caused by sub-pixel rendering(http://blogs.msdn.com/b/ie/archive/2012/02/17/sub-pixel-rendering-and-the-css-object-model.aspx?Redirected=true)

    to avoid above problem use below code


    if ($(window).scrollTop() >= ($(document).height() - $(window).height()-1))

    ReplyDelete
  58. Like this post...

    ReplyDelete
  59. if you are having this problem:

    Notice: Undefined index: last_msg_id in /opt/lampp/htdocs/reg/load_data.php on line 5

    Notice: Undefined index: action in /opt/lampp/htdocs/reg/load_data.php on line 6

    Just add @ to the variables like this @$last_msg_id and @$action, that should solve the problem.

    To stop the code from returning double data replace your javascript code with this:

    var bSuppressScroll = false;
    $(document).ready(function(){
    function last_msg_funtion()
    {
    var ID=$(".message_box:last").attr("id");
    $('div#last_msg_loader').html('add your loader image here');
    $.post("load_data.php?action=get&last_msg_id="+ID,
    function(data){
    if (data != "") {
    $(".message_box:last").after(data);
    window.bSuppressScroll = false;
    }
    $('div#last_msg_loader').empty();
    });
    };
    $(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height() && window.bSuppressScroll == false ){
    last_msg_funtion();
    window.bSuppressScroll = true;
    }
    });
    });

    ReplyDelete
  60. Hello All,

    I am working Image gallery website. Image serach page will work like google image search. On scroll it shows next results using jquery. How to display the same result if user refresh the page?


    Thanks,

    Sham

    ReplyDelete
  61. my scrolled div is appearing over 1st div instead of appearing down..y so

    ReplyDelete
  62. thanks man. nice code keep sharing.. :)

    ReplyDelete
  63. you must be on google,facebook or twitter like company

    ReplyDelete
  64. thanks it's working but have some errors
    You will find the solution in Obinna Okpala comment

    ReplyDelete
  65. Good one.
    could you tell me how to use this with scroll-able div

    ReplyDelete
  66. $last_msg_id=$_GET['last_msg_id'];
    $sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");

    is wide open to sql injection. It's no wonder people pick up bad habits when tutorials like this completely disregard the fundamentals.

    Make sure you validate $last_msg_id by casting to an integer:
    $last_msg_id = (int) $_GET['last_msg_id'];

    ReplyDelete
  67. Notice: Undefined index: last_msg_id in E:\xampp\htdocs\ehealth\scroll.php on line 5

    Notice: Undefined index: action in E:\xampp\htdocs\ehealth\scroll.php on line 6

    help me please...

    ReplyDelete
  68. How to set my LazyLoad slider after Half page scroll...Help me

    ReplyDelete
  69. Problems of this code on mouse scroll multiple time duplicate data show ........Please remove this problem

    ReplyDelete
  70. what is der inside the config.php file???
    reply asap

    ReplyDelete
  71. It's not working in various browsers like mozilla and also while scrolling content css tabs was not working.can you please help how to do?

    ReplyDelete
  72. ');
    if($db){
    }
    else{
    echo "db not found";
    }
    }else{
    echo "conection not found";
    }
    ?>

    ReplyDelete
  73. I guess the script posted here and that reflected in the demo are slightly different as the demo works fine but when you use the the script here it has the problem of double display of same data etc.

    can some one suggest a fix?

    ReplyDelete
  74. Hi guys, I try this code and it works, BUT when all the scripts are loaded inside a frame page doesn't work :(

    The code that I use for the frame page is:
    < frameset rows="100%, *" frameborder="no" framespacing="0" border="0" >
    < frame src="pagescript.php" name="mainwindow" frameborder="no" framespacing="0" marginheight="0" marginwidth="0" >< /frame >
    < /frameset >

    Any ideas? :(

    ReplyDelete
  75. this is what i need.....thank you so much

    ReplyDelete
  76. Thank you,But this staff has a bug.I call this bug as UpAndDown it means that the scroll ends we must scroll up a little and scroll down again to load data,Facebook has the best!!

    ReplyDelete
  77. I got duplicate rows. Do you know guys how to solve this?

    ReplyDelete
  78. I have changed the below function to prevent duplicates
    function last_msg_funtion()
    {
    if($('div#last_msg_loader img').length){
    //Which means previous one is in still load
    return;
    }
    //Other codes here
    };

    ReplyDelete
  79. this code work on browser but not working in mobile scroll wht i do

    ReplyDelete
  80. nice indentation ¬¬

    we are anonymous

    ReplyDelete
  81. what about this??

    Notice: Undefined index: last_msg_id in \\load_data.php on line 6

    Notice: Undefined index: action in \\load_data.php on line 7


    ReplyDelete
  82. this is not solving the problem:

    "Just add @ to the variables like this @$last_msg_id and @$action, that should solve the problem.
    "

    what should i do?

    ReplyDelete
  83. it works..although some of line code is error in (load_data.php), but overall everything is good, just add some logic condition on
    if(isset($_GET['last_msg_id']))
    {
    $last_msg_id = $_GET['last_msg_id'];
    }
    if(isset($_GET['action']))
    {
    $action=$_GET['action'];
    }else{ $action = ''; }

    so everything is worked

    ReplyDelete
  84. Hi,
    thank you for this tutorial, can you please show me how to do the same using jsp instead of php ?
    thanks, your help is appreciated.

    ReplyDelete
  85. when working on whole day i found this code..
    and it's working properly..

    thnx dude great work....

    ReplyDelete
  86. when i refresh my page it continuously scrolldown..how to prevent ?

    ReplyDelete
  87. Great work dude... Saved me lot of time

    ReplyDelete
  88. Hi
    this work correctly on my webpage but I lost my jcart working. plz help me...

    ReplyDelete
  89. Hi I am using ur logic for loading products on my products view page and i also need to add the sorting functionality .But for sorting it requires all the product, How to do?

    ReplyDelete
  90. Thank you! Just what I needed :D

    Is there any way to add jQuery Masonry to this :)

    ReplyDelete
  91. what is this line means $action <> "get". what <> means in php

    ReplyDelete
  92. Great tutorial...I just wanted to ask which software or photo editor you use for editing those images?

    ReplyDelete
  93. <> means 'not equal' its the same as != . <> is the old method i dont now if it works anymore

    ReplyDelete
  94. Hi, Nice Post...
    I am using this but how could we use this with filter.
    I am not able to pass the filter variable to load_second.php.
    please suggest..

    ReplyDelete
  95. How Can i Give Back To Scroll button For this loading page.

    ReplyDelete
  96. the code is working properly but sir page gets reload every time scroll down whats the problem

    ReplyDelete
  97. Does it work in Apple PC's?? Think $(window).scroll wouldn't work there??

    ReplyDelete
  98. This comment has been removed by a blog administrator.

    ReplyDelete
  99. This code is not working in mobile phone.

    ReplyDelete
  100. Notice: Undefined index: last_msg_id in C:\wamp\www\mytest\load_data_scrolling\load_data.php on line 5

    Notice: Undefined index: action in C:\wamp\www\mytest\load_data_scrolling\load_data.php on line 6
    Help Meee Plzzzzz

    ReplyDelete
  101. loadind data twice plz help

    ReplyDelete
  102. Thank you for beset tutorial and demo,

    When i use your code , when i load page and (Ctrl+Home) , (Ctrl+End), (Ctrl+Home) , (Ctrl+End), (Ctrl+Home) , (Ctrl+End), (Ctrl+Home) , (Ctrl+End),….with speed

    I have duplicate data , How can i do that ?

    Add Reply

    ReplyDelete
  103. It Does not work on Mobile Devices . Anybody here got solution for that ?

    ReplyDelete
  104. It was very good one and very helpul. Nice

    ReplyDelete
  105. load data while scroll using jquery is quite easy now

    ReplyDelete
  106. hello i need coding for when i search something it must display the text in same page without refreshing another page similarly like google in php .will u pls

    ReplyDelete
  107. var ID is not declared.
    If var ID is the same as the last ID the user may get slow load or duplicate entries.

    ReplyDelete
  108. I am having an issue with the way the entries are being loaded. After the first entries load, the other entries are loaded in a div but as the "full website". I have no idea what is wrong as I am not an expert with PHP. The site basically loads itself when trying to read the next set of entries into the last_msg_loader div. I need help!!!! Thanks

    ReplyDelete
  109. showing error on load.php undefined index last_mes_id and action

    ReplyDelete
  110. please upload a script after giving tick to checkbox data has to retrive without refreshing page

    Thank you

    ReplyDelete

mailxengine Youtueb channel
Make in India
X