Ajax Infinite Scroll Using jQuery, PHP and MySQL

We have covered tutorial on Ajax based pagination using jQuery. To display more content to user without navigating to other pages ajax pagination comes very handy. We have another great method to display more content to user without letting user to navigate to different page and it’s called Infinite scrolling. It’s good to load the content when user is at the end of page. There are various popular sites like Facebook uses this method to show news feeds to user. When you will reach the bottom of the window it will load new feeds. There are various jQuery plugin to do the job but it’s a small script so we will not use any jQuery plugin. We will write our own jQuery code to load new content on window scroll. We have used MySQL and PHP to display and store some sample data.

 infinite-scroll

[button_round color=”blue” url=”infotuts.com/demo/infinite-scroll-jquery”] Live Demo [/button_round]

Let’s see how we can implement infinite scrolling. Below is our code for script.js which is responsible for all the core action. As soon as scroll bar reaches the bottom of page this little script loads more content from database by calling scroll.php file.

Below is our code for scroll.js:

</p>
var ajax_arry=[];
 var ajax_index =0;
 var sctp = 100;
 $(function(){
 $('#loading').show();
 $.ajax({
 url:"scroll.php",
 type:"POST",
 data:"actionfunction=showData&page=1",
 cache: false,
 success: function(response){
 $('#loading').hide();
 $('#demoajax').html(response);

 }

 });
 $(window).scroll(function(){

 var height = $('#demoajax').height();
 var scroll_top = $(this).scrollTop();
 if(ajax_arry.length>0){
 $('#loading').hide();
 for(var i=0;i<ajax_arry.length;i++){
 ajax_arry[i].abort();
 }
 }
 var page = $('#demoajax').find('.nextpage').val();
 var isload = $('#demoajax').find('.isload').val();

 if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
 $('#loading').show();
 var ajaxreq = $.ajax({
 url:"scroll.php",
 type:"POST",
 data:"actionfunction=showData&page="+page,
 cache: false,
 success: function(response){
 $('#demoajax').find('.nextpage').remove();
 $('#demoajax').find('.isload').remove();
 $('#loading').hide();

 $('#demoajax').append(response);

 }

 });
 ajax_arry[ajax_index++]= ajaxreq;

 }
 return false;

 if($(window).scrollTop() == $(window).height()) {
 alert("bottom!");
 }
 });

});
<p style="text-align: justify;">

You can open db.php file and set the value of $limit to define how many rows must be loaded at once.

Let’s see our code for scroll.php:

</p>
<?php
include('db.php');

if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];

 call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
 $page = $data['page'];
 if($page==1){
 $start = 0;
 }
 else{
 $start = ($page-1)*$limit;
 }

 $sql = "select * from infinitescroll order by id asc limit $start,$limit";
 $str='';
 $data = $con->query($sql);
 if($data!=null && $data->num_rows>0){
 while( $row = $data->fetch_array(MYSQLI_ASSOC)){
 $str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p></div>";
 }
 $str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
 }else{
 $str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
 }
echo $str;
}
?>
<p style="text-align: justify;">

You can download the code and set up your local database with the SQL query given in demo files. Let me know what do you think of this little script and also suggest your awesome ideas to improve the script as well as our blog.


Posted

in

, , , ,

by

Tags:

Comments

16 responses to “Ajax Infinite Scroll Using jQuery, PHP and MySQL”

  1. Pritesh Avatar
    Pritesh

    instead of using window scroll event, can there be a SHOW MORE button on bottom, Clicking on that button should load the result of next page. what changes required to implement this.?

  2. Alex Avatar
    Alex

    Good Script ! I have 1 milion records ++++ and this is ok
    Thanks

  3. momo Avatar
    momo

    Thank you for beset tutorial and demo,

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

    I have duplicate data , How can i do that ?

  4. Nemod Avatar
    Nemod

    Hey great tutorial! Do you know Infinite AJAX Scroll (http://infiniteajaxscroll.com )? With that plugin I had infinite scroll in minutes, super easy!

  5. ilhan Avatar

    Thanks for tuts but when i added “!DOCTYPE html” first line on the page not working ? Any solution ???

  6. Brad Avatar
    Brad

    Hi Sanjeev

    Thanks for the tutorial.
    I have tried it but it isn’t working on mobile devices.
    Can you please advise what I can do?

  7. Rammehar Avatar
    Rammehar

    Great Post Sir

  8. gianni Avatar
    gianni

    Grazie perfetto

  9. Majid Avatar
    Majid

    Your code is not working for browser height bigger than 881px.

  10. Elizandro Avatar
    Elizandro

    Declare doctype first line on the page not working?

    Any solution ???

  11. Ahmad Avatar
    Ahmad

    my response is suppose to return some javascript and it is not exexuting the javascript in the browser, can you help me with that?

    1. Ahmad Avatar
      Ahmad

      Also, its not working on mobile devices

  12. Jtech Avatar

    Great article, I enjoyed the in depth look at infinite scrolling. We wrote a similar article on the topic of infinite scrolling. We focused more on the pitfalls of infinite scrolling and the best practices to avoid them.
    https://www.jtechcommunications.com/technical-blog-infinite-scrolling

  13. Divya Avatar

    You can give alto scroll for 3 scroll downs after tat a show more button to load further data