Load Data Dynamically on Page Scroll using jQuery AJAX and PHP

by Vincy. Last modified on September 12th, 2022.

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 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 the jQuery AJAX event handler. This is an alternate solution for the per-page navigation scenario.

View Demo

jQuery AJAX Scroll Down Event Handler

Javascript Event Handler

For loading the subsequent record sets, we have to know whether the scrollbar reached the bottom of the window.

load data on scroll output

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.

index.php (script in the HTML head section)

$(window).scroll(function() {
	if ($(window).scrollTop() == $(document).height() - $(window).height()) {
		if ($(".pagenum:last").val() <= $(".total-page").val()) {
			var pagenum = parseInt($(".pagenum:last").val()) + 1;
			getresult('getresult.php?page=' + pagenum);

		}
	}
});

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.

index.php (load result via ajax script in the HTML head)

function getresult(url) {
	$.ajax({
		url: url,
		type: "GET",
		beforeSend: function() {
			$('#loader-icon').show();
		},
		complete: function() {
			$('#loader-icon').hide();
		},
		success: function(data) {
			$("#faq-result").append(data);
		},
		error: function() { }
	});
}

PHP Page

PHP page requested by the AJAX scroll event handler is,

getresult.php

<?php
require_once ("db.php");
$perPage = 3;
$sql = "SELECT * from php_interview_questions";

$page = 1;
if (! empty($_GET["page"])) {
    $page = $_GET["page"];
}
$start = ($page - 1) * $perPage;
if ($start < 0) {
    $start = 0;
}
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
$pages = ceil($result->num_rows / $perPage);

$query = $sql . " limit " . $start . "," . $perPage;
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->get_result();

$output = '';
if (! empty($result)) {
    $output .= '<input type="hidden" class="pagenum" value="' . $page . '" />
                <input type="hidden" class="total-page" value="' . $pages . '" />';
    while ($row = mysqli_fetch_array($result)) {

        $output .= '<div class="question">' . $row["question"] . '</div >';

        $output .= '<div class="answer">' . $row["answer"] . '</div>';
    }
}
print $output;
?>

Other files of this example

We have seen the main code of this example above. Below are some of the other component of this example which helps to run this code in your PHP environment.

Landing page to append more content on page scroll

index.php

<div id="faq-result">
<?php include('getresult.php'); ?>
</div>
<div id="loader-icon">
   <img src="LoaderIcon.gif" />
</div>

Database connection script that creates the connection object

db.php

<?php
$connection = mysqli_connect("localhost", "root", "", "db_load_data");
?>

Database script having the create statement and the data of the tables

structure.sql

CREATE TABLE `php_interview_questions` (
  `id` int(8) NOT NULL,
  `question` text NOT NULL,
  `answer` text NOT NULL
);

--
-- Dumping data for table `php_interview_questions`
--

INSERT INTO `php_interview_questions` (`id`, `question`, `answer`) VALUES
(1, ' What are the widely used array functions in PHP?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nisi mi, lacinia id faucibus at, commodo dapibus turpis. Quisque fermentum arcu vel sem cursus placerat. Etiam egestas eu lorem aliquet finibus. Duis aliquet, nisl a condimentum varius, arcu mi mattis lectus, et volutpat turpis ipsum non ipsum. Donec fringilla id eros id elementum. Curabitur non euismod libero. Maecenas at nisi est.'),
(2, 'How to redirect using PHP?', 'Integer vel eros aliquam, efficitur odio sit amet, pharetra neque. Praesent convallis euismod lacus, a semper leo iaculis vitae. Cras ut nibh laoreet, ultricies neque eget, sodales felis. Morbi ut erat nec nibh ullamcorper ornare pellentesque sed lectus. Nam id mauris auctor, ultricies dui eu, placerat sapien.'),
(3, ' Differentiate PHP size() and count():', 'Vivamus eget est elit. Ut magna dolor, placerat sed risus ac, varius facilisis leo. Duis hendrerit, ante vitae volutpat eleifend, orci turpis malesuada ligula, sed hendrerit quam dolor sed eros. Suspendisse pulvinar orci non leo vehicula, et commodo leo pharetra. Donec fringilla id eros id elementum. Curabitur non euismod libero. Maecenas at nisi est.'),
(4, 'What is PHP?', 'Cras condimentum sapien ullamcorper pellentesque ornare. Nam varius augue sed sem luctus aliquam. Proin et euismod leo. Fusce a mi sit amet augue suscipit tempor vitae ac justo. Donec mattis nisl sed rutrum fringilla. Quisque vulputate purus quam, at dapibus leo commodo ut. Aliquam augue quam, mattis in maximus at, convallis et dui. Vivamus eget risus nec nibh semper tristique. Phasellus a eleifend libero, lacinia condimentum arcu. Suspendisse potenti.'),
(5, 'What is php.ini?', 'Donec blandit euismod tincidunt. Sed cursus tellus vulputate lacus rhoncus, sit amet consequat nunc mattis. Sed commodo, mauris et facilisis varius, sem turpis condimentum mauris, non gravida lorem orci sed velit. Ut augue mi, imperdiet sit amet commodo eget, posuere at tellus. Nunc euismod porttitor sollicitudin.');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `php_interview_questions`
--
ALTER TABLE `php_interview_questions`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `php_interview_questions`
--
ALTER TABLE `php_interview_questions`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

We are familiar with the above PHP script which we have already seen in the 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

↑ Back to Top

Share this page