my-programming-tutorials-logo

My Programming Tutorials

How To Create Infinite Scroll Pagination With PHP And Ajax

Last updated on by , 11 comments

In this tutorial, we are going to learn that how to create infinite scroll pagination with PHP and Ajax.

All of you probably must have seen this feature in some websites that you can load more content by just scrolling down.

It can be possible via AJAX. I hope all of you guys will be familiar with Ajax, if not please see what actually an AJAX is?

Let me show you some live examples of infinite scroll pagination, as you are a regular user of Facebook & Twitter etc. I bet you noticed that they use this kinda pagination. When you scroll down they load more contents on your timeline.

View Demo

infinite scroll pagination with php and ajax

In my previous article, I have covered the pagination with PHP and MySql, If you have not read it yet, then I suggest you read that article first. Because the pagination part will be done by PHP itself.

Requirements to create infinite scroll pagination with PHP and Ajax

1. GIF Loader

I have used Preloaders in this article. Preloader provides almost all type of animated GIF Loaders. It is necessary to show a loading process while fetching data asynchronously.

2. A jQuery plugin called Inview

Inview is a JQuery Plugin, which is designed to fire an event as soon as the targeted element appears on the user’s viewport.

You must have JQuery installed in your page to work with Inview. The important thing is, it works only with jQuery 1.8 & upwards. To learn more about Inview, visit Github jquery.inview.

Usage of Inview

$('#target_element_id').on('inview', function(event, isInView) {
    if (isInView) {

        // element is now visible in the viewport

    } else {

        // element has gone out of viewport

    }
});

Let’s dig into actual coding

1. HTML part

<div id="response">

    <!-- response(next page's data) will get appended here -->

    <!--we need to populate some initial data-->
    <?php
        $conn=mysqli_connect("localhost","my_user","my_password","my_db");
        // Check connection
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            die();
        }
        $sql = "SELECT * FROM table LIMIT 5";
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_assoc($res_data)){
            echo '<div>Demo'.$row["id"].'</div>';
        }
        mysqli_close($conn);
    ?>

</div>

<input type="hidden" id="pageno" value="1">
<img id="loader" src="loader.svg">

Lets split above HTML snippet and see what actually they will perform. So here we have Three elements #response, #pageno & #loader.

#response element would be the container for our fetched data. We will use AJAX request to fetch next page’s data and append it in #response element.

#pageno is a kind of page number counter, we are using it to identify that how much pages have loaded. We have set its default value to “1” so that it loads the first page first.

#loader will be placed at the last of the results as you can see it in the HTML snippet. When the user scrolls down, the Ajax function that will bring the data of the next page will get fired as soon as the #loader comes in the viewport.

2. AJAX JQuery Part

var nextPage = parseInt($('#pageno').val())+1;

$.ajax({
    type: 'POST',
    url: 'pagination.php',
    data: {
        pageno: nextPage
    },
    success: function(data){
        if(data != ''){							 
            $('#response').append(data);
            $('#pageno').val(nextPage);
        } else {								 
           $("#loader").hide();
        }
    }
});

Every time when #loader appears in the browser’s viewport then the above Ajax function gets fired and sends a POST request to the pagination.php file.

We are sending a nextPage number along with the POST request so that the pagination.php file can understand which page to load.

When execution of the Ajax function gets finished then pagination.php file returns next page’s data. We need to append that data in our #response element as you can see in the above snippet.

3. PHP part

$pageno = $_POST['pageno'];

$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;

As you can see from here the PHP pagination part has started, as I have suggested earlier you should read my previous article pagination with PHP and MySQL.

The SQL Query for Pagination

$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";

Let’s assemble the PHP pagination codes

We are going to put all the PHP codes in the pagination.php file, so go ahead and create the pagination.php file and put below codes into it.

<?php

    $pageno = $_POST['pageno'];

    $no_of_records_per_page = 10;
    $offset = ($pageno-1) * $no_of_records_per_page;

    $conn=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }

    $sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
    $res_data = mysqli_query($conn,$sql);

    while($row = mysqli_fetch_array($res_data)){

        echo '<div>Demo'.$row["id"].'</div>';

    }

    mysqli_close($conn);

?>

so PHP part has been done here.

Let’s assemble the Html and JQuery codes

<!DOCTYPE html>
<html>
<head>
    <title>Infinite Scroll Demo</title>

    <!-- JQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

    <!-- Inview Js (jquery.inview.js) -->
    <script src="jquery.inview.js"></script>

    <style>
        #response div{
            border: 1px solid lightgrey;
            height: 80px;
            margin-bottom: 5px;
            padding: 50px 0px 0px 0px;
            text-align: center;
        }
        #loader{
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

    <div id="response">

        <!-- response(next page's data) will get appended here -->

        <!--we need to populate some initial data-->
        <?php
            $conn=mysqli_connect("localhost","my_user","my_password","my_db");
            // Check connection
            if (mysqli_connect_errno()){
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
                die();
            }
            $sql = "SELECT * FROM table LIMIT 5";
            $res_data = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($res_data)){
                echo '<div>Demo'.$row["id"].'</div>';
            }
            mysqli_close($conn);
        ?>
    </div>

     <input type="hidden" id="pageno" value="1">
     <img id="loader" src="loader.svg">
     <script>
         $(document).ready(function(){
             $('#loader').on('inview', function(event, isInView) {
                 if (isInView) {
                     var nextPage = parseInt($('#pageno').val())+1;
                     $.ajax({
                         type: 'POST',
                         url: 'pagination.php',
                         data: { pageno: nextPage },
                         success: function(data){
                             if(data != ''){							 
                                 $('#response').append(data);
                                 $('#pageno').val(nextPage);
                             } else {								 
                                 $("#loader").hide();
                             }
                         }
                     });
                 }
             });
         });
     </script>
</body>
</html>

That’s all folks!!!, If you find this article helpful, don’t forget to share and subscribe us.

How To Create Infinite Scroll Pagination With PHP And Ajax
4.5 (90%) 10 votes

Advertisement
11 Responses
  1. Sam says:

    Hey Pandey,

    I tried getting this code to work but it won’t work for me. I also checked the demo code, and the demo code is totally different than what is posted here. Do you mind sharing this demo code, http://demo.myprogrammingtutorials.com/infinite-scroll-pagination/? Thanks,

    • Paritosh Pandey says:

      Hello @Sam,

      there was some problem with the inview js CDN, and couple of vital thing were missing, it was my bad. I have updated the whole codes, please give a try agian.

      Thank you

  2. jeeron says:

    Hello! This working so fine, thanks!
    have you got a tip for hide loading img after last result ?

    • Paritosh Pandey says:

      ohh! that’s my bad, I really forgot about that,
      Thank you for letting us know BTW
      I will definitely gonna update the article.
      Thanks again.

    • Paritosh Pandey says:

      all we need to do is just check the response of AJAX request whether it is blank or not like this :

      
      if(response != ''){
      								 
         $('#container').append(response);
      
      } else {
      								 
         $("#loader").hide();
      
      }
      
  3. Mario says:

    Hi,
    What fields form the mysql data table?
    Does the table used in the example (my_db) have only the id ($ row [“id”]) field?
    Can you send me a more complete table suggestion?
    Grateful
    Mario

    • Paritosh Pandey says:

      the “id” (auto increment) is necessary for paginating the rows, you can add as much as columns as you want.

  4. Mario says:

    Okay, all right.
    Send information about other tutorials …
    Thank you very much..

  5. jeeron says:

    Thanks a lot, i’ll waiting for code update.
    i have take a look on your demopage code source, and i have see :
    url: ‘data.php’, lastItem: lastItem success: function(response){ setTimeout(function(){ $(‘#container’).append(response); },2000);

    Just now need the data.php code 🙂

    Thanks 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.