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

Written by Saran on May 30, 2013, Updated June 5, 2017

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.

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.

Index Page

Create a UL element with ID "results", this is where we are going to display the results fetched from server. You can wrap it with a DIV element, it will give you more control when you style them with CSS:

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, the 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.

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.

About Sanwebe.com

Sanwebe.com was founded in 2011 by Saran Chamling. A blog truely inspired by the ever changing web development world. It is a small effort to provide useful tips, tutorials and related resources to web developers.