Load Data on Page Scroll using jQuery Ajax PHP from MySQL Database


Previously we’ve published many tutorials on load data from MySQL database in PHP. For example our last article – Load more data using jQuery Ajax and PHP, where data are loaded from the database by clicking on the load more link. But in this article, we’ll do it differently. This tutorial will show an automatic process to load more data from the database in PHP. Here we’ll build script for load data on page scroll using jQuery, Ajax, and PHP. It will be very user-friendly because the data would be loaded from the MySQL database automatically while scrolling the page down. Users are not needed to click any link for data load.

Let’s start the Load Data on Page Scroll with jquery and PHP tutorial. Before you begin, take a look on files structure.


Database Table Creation

Create a table named posts into the database (for example codexworld). Example SQL query for creating posts table is given below.

CREATE TABLE `posts` (
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Data will be fetched from this posts table and display in the data list. So, insert some data into the posts table for testing purpose.

Database Configuration (dbConfig.php)

dbConfig.php is a configuration file, in this file, we’ll create a database connection and select MySQL database.

//DB details
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword '';
$dbName 'codexworld';

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
"Unable to connect database: " $db->connect_error);


index.php File

This file contains some JavaScript and PHP code. On page load, the initial data is displayed from the posts table and more data would be fetched from the database while page scrolling.

JavaScript Code:
Load the JS library before writing JavaScript Code.

<script src="jquery.min.js"></script>

On page scroll, we’ll get the last displayed post ID (lastID) and the next posts from the getData.php file using Ajax. Once Ajax success method returns the posts data, the posts HTML would be appended to posts list.

        var lastID = $('.load-more').attr('lastID');
        if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){

PHP & HTML Code:

//Include DB configuration file
?> <div class="container"> <div class="row"> <div class="col-lg-12"> <h1>Load Data on Page Scroll using jQuery Ajax PHP from MySQL Database</h1> <div class="post-list" id="postList">             <?php
//get rows query
$query $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT 10");
$query->num_rows 0){ 
$row $query->fetch_assoc()){ 
$postID $row["id"];
?> <div class="list-item"><a href="javascript:void(0);"><h2><?php echo $row['title']; ?></h2></a></div>             <?php ?> <div class="load-more" lastID="<?php echo $postID?>" style="display: none;"> <img src="loading.gif"/> </div>            <?php ?> </div> </div> </div> </div>

getData.php File

Using the getData.php file, we’ll fetch the posts data from the MySQL database based on the last post ID and generate the posts list HTML. Ajax success method gets this HTML and renders the HTML content to the respective DIV element.

if(isset($_POST["id"]) && !empty($_POST["id"])){

//Include DB configuration file

//Get last ID
$lastID $_POST['id'];

//Limit on data display
$showLimit 5;

//Get all rows except already displayed
$queryAll $db->query("SELECT COUNT(*) as num_rows FROM posts WHERE id < ".$lastID." ORDER BY id DESC");
$rowAll $queryAll->fetch_assoc();
$allNumRows $rowAll['num_rows'];

//Get rows by limit except already displayed
$query $db->query("SELECT * FROM posts WHERE id < ".$lastID." ORDER BY id DESC LIMIT ".$showLimit);

$query->num_rows 0){
$row $query->fetch_assoc()){ 
$postID $row["id"]; ?>
        <div class="list-item"><a href="javascript:void(0);"><h2><?php echo $row["title"]; ?></h2></a></div>
<?php ?>
if($allNumRows $showLimit){ ?>
    <div class="load-more" lastID="<?php echo $postID?>" style="display: none;">         <img src="loading.gif"/>     </div>
<?php }else{ ?>     <div class="load-more" lastID="0">         That's All!     </div>
<?php }
    <div class="load-more" lastID="0">         That's All!     </div>

CSS Code

In our example script, the following CSS has used to design the posts list.

div.list-item {
    border-left: 4px solid #7ad03a;
    margin: 5px 15px 2px;
    padding: 1px 12px;
    -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
    box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
    height: 60px;
div.list-item p {
    margin: .5em 0;
    padding: 2px;
    font-size: 13px;
    line-height: 1.5;
.list-item a {
    text-decoration: none;
    padding-bottom: 2px;
    color: #0074a2;
    -webkit-transition-property: border,background,color;
    transition-property: border,background,color;-webkit-transition-duration: .05s;
    transition-duration: .05s;
    -webkit-transition-timing-function: ease-in-out;
    transition-timing-function: ease-in-out;
.list-item a:hover{text-decoration:underline;}
.load-more {
    margin: 15px 25px;
    cursor: pointer;
    padding: 10px 0;
    text-align: center;
.list-item h2{font-size:25px; font-weight:bold;text-align: left;}

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Anurag Said...
  2. Jeb Bush Said...
  3. Deepak K J Said...

Leave a reply