Auto Load More Data On Page Scroll (jQuery/PHP)

In previous article – Loading More Results (jQuery/PHP), the records are loaded when the users clicked on “Load more Data” button, which is great but how about loading database records automatically when user scrolls down to the bottom of the page? The technique can be seen in Twitter, Facebook and several other websites. Let’s use examples from previous article, with some modification we can create Ajax based auto loading script, which loads records when user scrolls to bottom of the page.

auto-load-records-on-scroll

MySQL Table

Run MySql query below to create a table in MySql for this demo. You can also find a sql file in download, which you can import in PhpMyAdmin.

1
2
3
4
5
6
CREATE TABLE IF NOT EXISTS `paginate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `message` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;

Configuration

Let’s start with a configuration file to store our MySql database username and password.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$db_username = 'xxxxx';
$db_password = '';
$db_name = 'xxxxxx';
$db_host = 'localhost';
$item_per_page = 5;

$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
//Output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

?>

Index Page

Our HTML page contains a DIV container called “results”, where we will append records returned from server. Another element contains a loading image, which we will show while the results are loading and will be replaced with a message once we reach the end of record.

1
2
3
4
<div class="wrapper">
    <ul id="results"><!-- results appear here --></ul>
    <div class="loading-info"><img src="ajax-loader.gif" /></div>
</div>

jQuery

I have made few changes in jQuery code below. The .click() method is replaced with .scroll(), our code can now detect the page scroll, and auto loads remaining data when user scrolls to bottom of the page.

Just make sure, height of initially loaded content is greater than the height of page itself for scroll to work. Which means if there’s no vertical scrollbar in browser, you might want to increase $item_per_page number in PHP config script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var track_page = 1; //track user scroll as page number, right now page number is 1
var loading  = false; //prevents multiple loads

load_contents(track_page); //initial content load

$(window).scroll(function() { //detect page scroll
    if($(window).scrollTop() + $(window).height() >= $(document).height()) { //if user scrolled to bottom of the page
        track_page++; //page number increment
        load_contents(track_page); //load content  
    }
});    
//Ajax load function
function load_contents(track_page){
    if(loading == false){
        loading = true;  //set loading flag on
        $('.loading-info').show(); //show loading animation
        $.post( 'fetch_pages.php', {'page': track_page}, function(data){
            loading = false; //set loading flag off once the content is loaded
            if(data.trim().length == 0){
                //notify user if nothing to load
                $('.loading-info').html("No more records!");
                return;
            }
            $('.loading-info').hide(); //hide loading animation once data is received
            $("#results").append(data); //append data into #results element
       
        }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
            alert(thrownError); //alert with HTTP error
        })
    }
}

Fetching Database Records

The page number passed to PHP script using jQuery $.post() method in script above, is used to determine the position of the records in database query as you can see in PHP script below. I am using MySqli Prepared Statements to fetch the records, which is very secure and faster way. If you are confused or curious about MySqli, you can see PHP MySqli Basic usage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
    header('HTTP/1.1 500 Invalid page number!');
    exit();
}

//get current starting point of records
$position = (($page_number-1) * $item_per_page);

//fetch records using page position and item per page.
$results = $mysqli->prepare("SELECT id, name, message FROM paginate ORDER BY id DESC LIMIT ?, ?");

//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
//for more info https://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$results->bind_param("dd", $position, $item_per_page);
$results->execute(); //Execute prepared Query
$results->bind_result($id, $name, $message); //bind variables to prepared statement

//output results from database
while($results->fetch()){ //fetch values
    echo '<li>'.$id.') <strong>'.$name.'</strong> : '.$message.'</li>';
}
?>

Download Demo

  1. When u refresh at the bottom of the page, some rows are missing…

     Reply
  2. what if i wanna create overflow x:scroll and make it the trigger for autoload?

     Reply
  3. what should i do if i wanna change from scroll overflow y to scroll overflow x ??
    iam trying
    if($(window).scrollBottom() + $(window).width() >= $(document).width())

     Reply
  4. Very Nice tutorial. i want to use it for http://howcanisolve.com . is it work with all browsers?

     Reply
  5. Thanks for sharing! :)

    From
    Uganda, East Africa

     Reply
  6. Great tutorial

     Reply
  7. thanks for the post,,,,great tutorial

     Reply
  8. Nice and easy! Thanks!

     Reply
  9. Found script jumping records on fast scrolling
    So modified this

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $(window).scroll(function() { //detect page scroll
         if($(window).scrollTop() + $(window).height() &gt;= $(document).height()) { //if user scrolled to bottom of the page
              function checkVariable() {
                   if(loading == false){
                       track_page++; //page number increment
                       load_contents(track_page); //load content   
               }
              }
              $('.loading-info').show(); //show loading animation
              setTimeout(checkVariable,1000);  
         }
    });
     Reply
  10. suggestion for fade effect on display

    $(data).hide().appendTo(“#results”).fadeIn(1000);

     Reply
  11. That nice, do you have “Auto Load More Data” plugin for wordpress?
    If not, I need to convert your code to wordpress plugin.
    Anyway thanks,

     Reply
  12. This artical was more helpful to me. Thank you!

     Reply
  13. hi, I hope you make the same tutorial for CodeIgniter. thanks

     Reply
  14. its not working for me
    hope u can check and tell me the error
    the page is not loading by itself whn i try to inspect (ctrl+shift+I) it loads

     Reply
  15. Thanks a lot for all tutorials. are awesome. I learn a lot.

     Reply
  16. hi friend i i don’t know how to correct the error of ajax utf8 decode because my all my data are with arabic language and i see result like this ??????????? if someone have solution please tell me and thank you

     Reply
    • Try using mysqli_set_charset($conn, “utf8”); before your mysqli_query.

      $conn is the mysqli_connect().

  17. Nice post save my time to get this point.

     Reply
  18. Does anyone know how to do the same using a database in postgresql instead of MySQL?
    Any website or Manual?
    I tried to use this one and change it but it is not working.

    config.php
    connect_error) {
    die(‘Error : (‘. $db->connect_errno .’) ‘. $db->connect_error);
    }
    ?>

    Not really sure on how to change the autoload_process.php and index.php

    I just changed the $mysqli for $db.

    THANKS

     Reply
  19. works well on opera n firefox but does not work on chrome

     Reply
  20. Hi I have a problem, im using bootstrap and using pills/tabs, now when I go to other tab, the window height function seems not working. can you suggest any thing to do?

     Reply
  21. Please, where should i save the PHP file?

     Reply
  22. Hi,
    Thanks for sharing code, it very helpful,. i have one problem, this load more i need center page. when i am going footer section it will works,.

     Reply
  23. Good, Could you please let me know if I want to load pages on scroll let say 3 pages on scroll at a time and then there is button to click to load more and then on click 1 page can be loaded until there is some content on the page?? Thanks

    Regards
    Sateesh
    http://www.savedimes.com

     Reply
  24. Great tutorial. Made my day. J

    It would be good to have a ‘show more’ button after scrolls down. But, it doesn’t load more records if, on the first screen, if there’re not enough records (example, items_per_group= 2) to enable first scroll. This behavior can be tacked.

    Great post. Thx

     Reply
  25. this file won’t download
    please fix it or email it to please
    Thank you
    Sam

     Reply
  26. Nice tutorial by the way. save my day

     Reply
  27. will this work on MVC framworks like CodeIgniter?

     Reply
  28. It can be better if You can give alto scroll for 3 scroll downs after tat a show more button to load further data

     Reply
Message Type : Question Comment ?
  • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
  • Comment : Short comments and questions.