How to Create Facebook Like Infinite Scroll Pagination using PHP and jQuery

by Vincy. Last modified on July 3rd, 2022.

Seamless UI / UX is a must for your application to standout in this noisy web world. Every day we are seeing revolutionary changes with innovations in web design. One such UI that has changed pagination forever is the infinite page scroll. The Facebook uses it in its wall which is the primary UI for the users.

The infinite scroll replaces the traditional pagination design with page numbers and navigation links. Displaying paginated results with the usual navigation link is almost outdated. Let us see about how to implement the infinite scroll pagination like Facebook using PHP and jQuery.

In a previous tutorial, we have seen a an example of creating pagination using PHP with AJAX. We have also seen pagination example without AJAX on how to load dynamic data on the page scroll. With the reference of those codes, we can implement the Facebook like content loading with infinite page scroll.

I have used PHP, MySQL with jQuery in this example for this type of dynamic content loading. On the page scroll event, the AJAX request is sent to access PHP by sending the page offset. In the PHP file, the page offset and other params are received by using the appropriate request methods. These params and the perpage constant are used for calculating the query limit to retrieve the data to be loaded dynamically.

Facebook-like-Infinite-Scroll-Output

If you are looking for PHP CRUD with search and pagination using AJAX refer the linked article.

HTML Container to Load Dynamic Results

This HTML code loads jQuery to execute the AJAX script to fetch the database result without page refresh. In this HTML, there is a container to load dynamically that are retrieved via AJAX request. Initially, it loads the first block of data from the database. And then, the subsequent AJAX request will get the content to be appended to the bottom of the existing content.

<div class="post-wall">
    <div id="post-list">
        <?php
            require_once ('db.php');
            $sqlQuery = "SELECT * FROM tbl_posts";
            $result = mysqli_query($conn, $sqlQuery);
            $total_count = mysqli_num_rows($result);
            
            $sqlQuery = "SELECT * FROM tbl_posts 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['content'], 0, 100);
                ?>
        <div class="post-item" id="<?php echo $row['id']; ?>">
            <p class="post-title">
                <?php echo $row['title']; ?>
            </p>
            <p>
                <?php echo $content; ?>
            </p>
        </div>
        <?php
            }
        ?>
    </div>
    <div class="ajax-loader text-center">
        <img src="LoaderIcon.gif"> Loading more posts...
    </div>
</div>

jQuery AJAX Content Loading On Page Scroll

The AJAX script is added inside the $(window) scroll event handler. This script will be executed once the user scrolls down and touches the bottom of the page. On each scroll, the page offset is updated and preserved in a hidden field. This offset will be sent with the AJAX request while accessing PHP to get database result. On successful AJAX response, data is received and appended to the existing page content. While processing the AJAX request, a loader image is shown to intimate the user that the content is getting loaded.

<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) {
        	   setTimeout(function() {
                $('.ajax-loader').hide();
            $("#post-list").append(data);
            windowOnScroll();
        	   }, 1000);
        }
   });
}
</script>

Read Recent Posts using PHP

This PHP code establishes the database connection at the beginning of the program. It receives the AJAX params and calculates the query limit with the page offset and the per page limit. By using the calculated query limit the results are fetched from the database and returned as the AJAX response.

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

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

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


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

Database Script

This SQL script is used to create the database table and insert the data to be read and load dynamically on the page scroll event.

--
-- Table structure for table `tbl_posts`
--

CREATE TABLE IF NOT EXISTS `tbl_posts` (
`id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `link` varchar(255) NOT NULL,
  `content` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_posts`
--

INSERT INTO `tbl_posts` (`id`, `title`, `link`, `content`) VALUES
(1, 'How to reduce or compress image size while uploading using PHP', 'https://phppot.com/jquery/jquery-sidebar-expand-collapse/', 'It is very common to upload images to the server or website by the users and admins. Users mostly upload their images for setting their profile picture or to submit documents and so on. But most of the time images are uploaded by the users are not optimized for the web, thus taking much more ...'),
(2, 'Store and retrieve image from database using PHP and MySQL', 'https://phppot.com/jquery/jquery-sidebar-expand-collapse/', 'Upload and store an image into the database and later retrieve that image from the database is very easy and simple. But before store into the database table, the image should be encoded using base64_encode() function. So, in this tutorial, I will show you how to store and retrieve image from database using PHP and MySQL ...'),
(3, 'Login with Facebook using JavaScript SDK', 'https://phppot.com/jquery/jquery-sidebar-expand-collapse/', 'Login with Facebook using JavaScript SDK provides an easy and simple way to integrate login system to your website without any registration. My earlier tutorial has shown how to login with Facebook using PHP SDK and MySQL in a website. In this tutorial, I will demonstrate you step by step process to learn how to Login with Facebook using ...'),
(4, 'Login with Facebook using PHP and MySQL', 'https://phppot.com/jquery/jquery-sidebar-expand-collapse/', 'Registration through filling a long form is a headache to any user. After seeing such big form they run away. But short registration process helps to get more subscribers for your website. Meanwhile, Facebook is the largest social network in Earth and billions of users. Facebook provides PHP SDK through which you can easily integrate registration and login system ...'),
(5, 'Create a Facebook App ID for your website', 'https://phppot.com/category/php/', 'This article will show you how to create a Facebook app and get the app ID and app secret code from it. If you wish to use Facebook social, like, login button on your website, then you will need these app ID and secret code. In order to create a Facebook application, you will need ...'),
(6, 'Simplest way to add cross browser jQuery date and time picker in web page', 'https://phppot.com/category/php/', 'In this tutorial, I will show you how to add cross browser jQuery date and time picker in the web page. It is a plugin, and it is very simple and easy to implement. Also, this jQuery datetimepicker plugin provides various options to customize datetimepicker as per your requirements. This tutorial helps you to add jQuery date and time ...'),
(7, 'Add TinyMCE editor in PHP or HTML', 'https://phppot.com/category/php/', 'When you need to save formatted text or HTML content from users on your website, using any editor like TinyMCE, you need a textarea field. TinyMCE editor is web based WYSIWYG editor which enables you to convert HTML textarea field to an editor. The TinyMCE editor is converting the formatted text into HTML when the form is submitted to the ...'),
(8, 'Multi-step form processing using PHP with jQuery form validation', 'https://phppot.com/category/php/', 'This tutorial will help you to understand how multi-step form processing will work. Here in the tutorial, we will achieve this using PHP. Apart from multi-step form processing, you will also learn how to do form validation using the help of jQuery. Multi-step form processing is very useful functionality when users have to input too much ...'),
(9, 'Upload files to the server using jsp and servlet', 'https://phppot.com/category/php/', 'Upload files to the server using JSP and servlet is a very easy and a common task in Java. The following example will give you a clear idea about how to upload files to the server using JSP and servlet. But before start coding, you need to know some important things. Like, “enctype=multipart/form-data“,  “HTTP POST“ ...'),
(10, 'PHP login ', 'https://phppot.com/category/php/', 'In this tutorial, I will show you how to do PHP login with PDO connection. Unlike MySQL or SQL database specific. You can connect and use any database using PDO. Different databases may have slightly different connection methods, but its very easy to switch. User_Details Table Create the below table in the database ...'),
(11, 'Add Google Map with multiple markers to your website', 'https://phppot.com/category/jquery/', 'This tutorial, will help you to integrate or add Google Map with multiple markers to your website. You can also visit the following link, if you want to add Google Map with a single marker to your website. We will use Google Maps API for displaying the Google Map with your desired locations. HTML code — Add ...'),
(12, 'jQuery digital clock plugin', 'https://phppot.com/category/jquery/', 'Hi friends, in this tutorial, I will show you how to create a simple jQuery digital clock plugin with the help of jQuery and CSS. This clock displays dynamic time. Here is nothing hard enough to understand. Simple HTML, CSS, and jQuery codes are used here. HTML – jQuery digital clock The HTML is very ...'),
(13, 'Add Google Map with a marker to your website', 'https://phppot.com/category/jquery/', 'The easiest way to find an address is Google Map. It shows the address with different and shortest routes. You can easily add Google Map with a marker to your website. The marker is your address. In this tutorial, I will tell you how to add Google Map to your website. We will use Google ...');

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

--
-- AUTO_INCREMENT for table `tbl_posts`
--
ALTER TABLE `tbl_posts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=23;

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Create Facebook Like Infinite Scroll Pagination using PHP and jQuery”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page