support@codebucket.net

How to create Infinite Scroll Pagination using PHP and jQuery

How to create Infinite Scroll Pagination using PHP and jQuery

K. M. Shawkat Zamil | November 16, 2022

Hello Developers,

In this tutorial, I will show you how to make infinite pagination using PHP and jQuery. This process is raw, essential, and straightforward. For that, you can use it in your project. Let's start.

 

First Step: Database connection

 

First, you need to create a file named db.php and create the database connection. Here I use my local PC wamp server. I created a database named 'test' and a table named 'sample_data'.

 

/db.php

<?php
	$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error($conn));
?>

 

Second Step: Create the index.php page

 

In the index.php file, I have simple write some HTML code to show my main data. Also added jQuery to my work. In the code, you need to add the db.php file which we created in the first step. After adding the file, write some get queries to fetch the data from the database.

 

<?php

require_once ('db.php');
$sqlQuery = "SELECT * FROM sample_data";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);

$sqlQuery = "SELECT * FROM sample_data ORDER BY id DESC LIMIT 7";
$result = mysqli_query($conn, $sqlQuery);

?>

 

After adding that code, you need to add some HTML lines to show your data. I have fetched my 'sample_data' and shown using a while loop. Furthermore, add a loader to wait while fetching the next data.

 

while ($row = mysqli_fetch_assoc($result)) {
	$content = substr($row['name'], 0, 100);
	?>
	<div class="post-item" id="<?php echo $row['id']; ?>">
		<p class="post-title">Age: <?php echo $row['age']; ?></p>
		<p class="post-title">City: <?php echo $row['city']; ?></p>
		<p><?php echo $content; ?></p>
	</div>
	<?php
	}
	?>
</div>
<div class="ajax-loader text-center">
	<img src="LoaderIcon.gif"> Loading more posts...
</div>

 

Now come to the main beauty. We will write a function to get the scroll behavior to get the page ending and make the ajax call to fetch the next data. 

 

$(document).ready(function(){
        windowOnScroll();
});
function windowOnScroll() {
       $(window).on("scroll", function(e){
        if ($(window).scrollTop() == $(document).height() - $(window).height()){
            if($(".post-item").length < $("#total_count").val()) {
                var lastId = $(".post-item:last").attr("id");
                getMoreData(lastId);
            }
        }
    });
}

function getMoreData(lastId) {
       $(window).off("scroll");
    $.ajax({
        url: 'getMoreData.php?lastId=' + lastId,
        type: "get",
        beforeSend: function ()
        {
            $('.ajax-loader').show();
        },
        success: function (data) {
			console.log(data);
        	   setTimeout(function() {
                $('.ajax-loader').hide();
            $("#post-list").append(data);
            windowOnScroll();
        	   }, 1000);
        }
   });
}

 

Here we call the next level of data in a separate file named getMoreData.php

 

/getMoreData.php

<?php
require_once('db.php');

$lastId = $_GET['lastId'];
$sqlQuery = "SELECT * FROM sample_data WHERE id < '" .$lastId . "' ORDER BY id DESC LIMIT 7";

$result = mysqli_query($conn, $sqlQuery);


while ($row = mysqli_fetch_assoc($result))
 {
    $content = substr($row['name'],0,100);
    ?>
    <div class="post-item" id="<?php echo $row['id']; ?>">
        <p class="post-title">Age <?php echo $row['age']; ?></p>
        <p class="post-title">City: <?php echo $row['city']; ?></p>
        <p><?php echo $content; ?></p>
    </div>
    <?php
}
?>

 

The complete index page code is given below:

 

/index.php

<!DOCTYPE html>
<html>
<head>
<title>How to Create Infinite Scroll Pagination using PHP
    and jQuery</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
    font-family: Arial;
    background: #e9ebee;
    font-size: 0.9em;
}

.post-wall {
    background: #FFF;
    border: #e0dfdf 1px solid;
    padding: 20px;
    border-radius: 5px;
    margin: 0 auto;
    width: 500px;
}

.post-item {
    padding: 10px;
    border: #f3f3f3 1px solid;
    border-radius: 5px;
    margin-bottom: 30px;
}

.post-title {
    color: #4faae6;
}

.ajax-loader {
    display: block;
    text-align: center;
}
.ajax-loader img {
    width: 50px;
    vertical-align: middle;
}
</style>
</head>
<body>
    <div class="post-wall">
        <div id="post-list">
            <?php
            require_once ('db.php');
            $sqlQuery = "SELECT * FROM sample_data";
            $result = mysqli_query($conn, $sqlQuery);
			//echo '<pre>'; print_r($result); exit();
            $total_count = mysqli_num_rows($result);
            
            $sqlQuery = "SELECT * FROM sample_data ORDER BY id DESC LIMIT 7";
            $result = mysqli_query($conn, $sqlQuery);
            ?>
            <input type="hidden" name="total_count" id="total_count"
            value="<?php echo $total_count; ?>" />

            <?php
            while ($row = mysqli_fetch_assoc($result)) {
                $content = substr($row['name'], 0, 100);
                ?>
                <div class="post-item" id="<?php echo $row['id']; ?>">
                    <p class="post-title">Age: <?php echo $row['age']; ?></p>
                    <p class="post-title">City: <?php echo $row['city']; ?></p>
                    <p><?php echo $content; ?></p>
                </div>
                <?php
                }
                ?>
            </div>
            <div class="ajax-loader text-center">
                <img src="LoaderIcon.gif"> Loading more posts...
            </div>
    </div>

<script type="text/javascript">
$(document).ready(function(){
        windowOnScroll();
});
function windowOnScroll() {
       $(window).on("scroll", function(e){
        if ($(window).scrollTop() == $(document).height() - $(window).height()){
            if($(".post-item").length < $("#total_count").val()) {
                var lastId = $(".post-item:last").attr("id");
                getMoreData(lastId);
            }
        }
    });
}

function getMoreData(lastId) {
       $(window).off("scroll");
    $.ajax({
        url: 'getMoreData.php?lastId=' + lastId,
        type: "get",
        beforeSend: function ()
        {
            $('.ajax-loader').show();
        },
        success: function (data) {
			console.log(data);
        	   setTimeout(function() {
                $('.ajax-loader').hide();
            $("#post-list").append(data);
            windowOnScroll();
        	   }, 1000);
        }
   });
}
</script>
</body>
</html>

 

The complete code is added to a GitHub repository. You can also download the code from here: GitHub Source Code

 

Hope this tutorial will help in the development journey.

 

Read More: Laravel Contents

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.