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.

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.

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

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

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.

New Comments

About Sanwebe

Welcome to sanwebe.com, a blog 100% inspired by our ever changing web development world, it's a small effort to provide useful related resources, tips and tutorials to web developers and newbies. Blog was launched back in 2011, and recently been moved from saaraan to sanwebe.com, blog needs some catching up to do, but your valuable feedbacks will always help.