My Programming Tutorials

My Programming Tutorials

How To Create Infinite Scroll Pagination With PHP And Ajax

Last updated on by , 34 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>

There is a JavaScript Plugin called Infinite Scroll available to save your time, but I personally won’t recommend you to use this.

I know you all probably would wondering,  why would I suggest that?

It is because this JavaScript plugin contains a JS file and by using this plugin you might end up with some extra kilobytes, which definitely gonna hamper your website’s load time.

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

Author Info

Paritosh Pandey

He loves Technology

Advertisement

34 responses to “How To Create Infinite Scroll Pagination With PHP And Ajax”

  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 🙂

  6. HJ says:

    Can this easily be implemented on WordPress and what if we don’t want to do “pagination” but we want articles to load for example how Reuters does it, when one article finishes the next one appears.

    https://www.reuters.com/article/us-maldives-politics-china/after-building-spree-just-how-much-does-the-maldives-owe-china-idUSKCN1NS1J2

    • Paritosh Pandey says:

      that is totally different approach. However the wordpress is a great platform and I’m sure there would be a lots of plugins to do this kind of page changing techniques.

  7. Cornelius Basua Ziemah says:

    Demo Page not working

  8. Cornelius Basua Ziemah says:

    Thank you.

  9. How do I make it possible to load data before, such as 300px before “loader image” enters the view port ? Thanks.

    • Paritosh Pandey says:

      you can modify inview.js file in this case.

      size = {height : (w.innerHieght - 300)} at line 58.

  10. Aleeza Gul says:

    Hello,

    I need the code pagination through ajax not need loader as you created before in previous PHP & MYSQL.

    Kindly please can you help me so how can I create the pagination through ajax with First, previous, next, last.

    Thanks
    Aleeza

    • Paritosh Pandey says:

      Hello @Aleeza,

      instead of firing next page data when loader shows up, you could use your pagination buttons as well.

      
          
          $("#next").click(function(){
      
              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();
                      }
                  }
              });
      
          });
      
          $("#prev").click(function(){
      
              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();
                      }
                  }
              });
          
          });    
      
      
      

      Regards,

  11. Aleeza Gul says:

    Hello, Sir Paritosh Pandey

    kindly can you help me?

    I have a simple 4 tab/step input form using Bootstrap 3 which needs Javascript field validation. I have been using this validator and would prefer that you used it also: https://github.com/1000hz/bootstrap-validator I would like the modal signup form to open when the page loads I would like the fields on each step of the form to be validated before the user can click the ‘Next’ button. I don’t want the visitor to be able to leave the modal window until the fields are properly filled in. A valid entry in each field is required. Also… – The Looking For: field can have more than one items checked. – The Birthrate: field must have a month,date and year. – The valid entries in the Username and Password are as shown in the placeholder text. The page is here: https://www.tucker.ca/may24.html Click “Open Modal” to see the form that we are working on

    Kindly please help me to solve this problem.

    Thanks
    Aleeza Gul

  12. salman khan says:

    any boddy is there to help me in doing like this in codeigniter???

  13. Merhabalar, siteme yüklemek isityorum. Yardımcı olurmusunuz. Teşekkürler – afyonkenthaber.com

  14. yalo says:

    thank you very much
    simple
    easy to custom

  15. Timothy Oluwole says:

    Hello Admin…This pagination does not capture new incoming data after the page has been fully loaded.please throw more light on this.thank for your favourable response

  16. John says:

    Doesn’t work data loading. Only work if open dev tool window and scroll the page up & down. When you update the code?

  17. Tony says:

    It seems that if you do fast scrolling (as I do), the script does not execute. What this does is that I get stuck staring at the loader image, but nothing happens. If I scroll back up a bit, and then back down (slowly) it will work as intended.

    It seems that the script executes at a narrow point when the image comes into view, but not when it is actually being visible. Perhaps checking for an interval, say 0-to-300px from bottom would be a good idea, and that the script executes when the image is at any point within that interval?

    • Paritosh Pandey says:

      Hi @Tony

      Thank you for your valuable suggestion, and definitely I’ll gonna implement some smart approach here as this script highly in need of.

      Currently in this script pagination function is getting invoked when the loader element gets appeared in viewport, which demonstrate a basic fundamental approach for an infinite scroll feature.

  18. Parabéns, deu certo aqui, até dei uma incrementada para proteção do arquivo.

  19. Angel says:

    You need to add autocomplete=”off” in the , i haved a glitch on page refresh and that solved it for me.

  20. ken says:

    the loader is not working

  21. wefacecook says:

    This script really requires a valid demo to demonstrate its potential.

    The demo page https://demo.myprogrammingtutorials.com/infinite-scroll-pagination/ is a 404.

Leave a Reply

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