Load Data Dynamically on Page Scroll using jQuery AJAX and PHP

In this tutorial, we are going to see about loading data into a web page dynamically as the user scrolls it. We will be using jQuery and AJAX for the dynamic load on the scroll. We have already seen about how to load dynamic data into a form collection field. It was for a specific field alone and now we are going to see a page on the whole.

Initially, we will show a limited number of results on page load. The subsequent bunch of records will be shown while scrolling down the page using jQuery AJAX event handler. This is an alternate solution for per-page navigation scenario.

View Demo

jQuery AJAX Scroll Down Event Handler

Javascript Event Handler

For loading subsequent record set, we have to know whether the scrollbar reached the bottom of the window. The following Javascript event handler will check if the scroll has reached the bottom and if it reaches then it will fire the AJAX call.

if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".pagenum:last").val() <= $(".rowcount").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;

AJAX Function

As the user keeps scrolling, the AJAX call will be continuously invoked until data reaches the end of the record in the database. Following is the AJAX function that shows the loading icon and retrieves data from the backend and shows it.

function getresult(url) {
url: url,
type: "GET",
data:  {rowcount:$("#rowcount").val()},
beforeSend: function(){
complete: function(){
success: function(data){
error: function(){} 	        


PHP Page

PHP page requested by the AJAX scroll event handler is,

$db_handle = new DBController();
$perPage = 10;

$sql = "SELECT * from php_interview_questions";
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query =  $sql . " limit " . $start . "," . $perPage; 
$faq = $db_handle->runQuery($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
$output = '';
if(!empty($faq)) {
$output .= '<input type="hidden" class="pagenum" value="' . $page . '" /><input type="hidden" class="rowcount" value="' . $_GET["rowcount"] . '" />';
foreach($faq as $k=>$v) {
 $output .=  '<div class="question">' . $faq[$k]["question"] . '</div>';
 $output .= '<div class="answer">' . $faq[$k]["answer"] . '</div>';
print $output;

We are familiar with the above PHP script which we have already seen in jQuery AJAX pagination tutorial. Presently this PHP script returns 10 records for each scroll event since we have set it as the per-page limit.

View DemoDownload

This jQuery code tutorial was published on October 8, 2014.

↑ Back to Top