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.

Configuration

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


qli = new mysqli($db_host, $db_username, $db_password,$db_name);
?>

Index Page

Before we write our jQuery code, we need to know the total records in the table, and break them into page numbers.

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 additional data when user scrolls to bottom of the page.


HTML code below should be placed within the body tag of the page, the results will appear inside the results element, and loading animation should appear only when user scrolls down to the bottom.


loading Process

Create a PHP file with code below, when the group number is passed to “autoload_process.php” using jQuery .post() method, we need starting point of record, and number of records to display per group. The MySQL LIMIT clause can be used to limit the results, we’ll just pass these two values as arguments, and have our records fetched.