Load Content on Page Scroll with jQuery and AJAX

The infinite page scroll you have seen on the social networking sites – Facebook, Twitter, or on e-commerce websites where the new content is automatically loaded when scrolling down to the web page.

For implementing this functionality I am jQuery to detect page scroll when the user reaches the end of the web page then send an AJAX request to load new content.

Load Content on Page Scroll with jQuery and AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML & PHP
  4. AJAX
  5. jQuery
  6. CSS
  7. Demo
  8. Conclusion

1. Table structure

I am using posts table in the example.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for the database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. HTML & PHP

I set the number of rows to fetch at a time to 3 ($rowperpage=3).

NOTE – Update the value of $rowperpage according to your requirement.

Count the total number of records and fetch the first 3 records from the posts table and create a layout.

Created 3 hidden fields –

  • The <input id='start'> store current row position.
  • The <input id='rowperpage'> store number of rows fetch at a time.
  • The <input id='totalrecords'> store total number of records.

Using these values when sending AJAX request.

Completed Code

<div class="container">

<?php

 include "config.php";

 // Row per page
 $rowperpage = 3;

 // counting total number of posts
 $allcount_query = "SELECT count(*) as allcount FROM posts";
 $allcount_result = mysqli_query($con,$allcount_query);
 $allcount_fetch = mysqli_fetch_array($allcount_result);
 $allcount = $allcount_fetch['allcount'];

 // select first 3 posts
 $query = "select * from posts order by id asc limit 0,$rowperpage ";
 $result = mysqli_query($con,$query);

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

   $id = $row['id'];
   $title = $row['title'];
   $content = $row['description'];
   $shortcontent = substr($content, 0, 160)."...";
   $link = $row['link'];
 ?>

   <div class="post" id="post_<?php echo $id; ?>">
     <h2><?php echo $title; ?></h2>
     <p>
       <?php echo $shortcontent; ?>
     </p>
     <a href="<?= $link ?>" target="_blank" class="more">More</a>
   </div>

 <?php
 }
 ?>

  <input type="hidden" id="start" value="0">
  <input type="hidden" id="rowperpage" value="<?= $rowperpage ?>">
  <input type="hidden" id="totalrecords" value="<?= $allcount ?>">

</div>

4. AJAX

Create ajaxfile.php file.

Read POST start and rowperpage values and assign to the variables.

Fetch records from posts table where use $start and $rowperpage in LIMIT.

Loop on the fetched records and create HTML string.

Return $html.

Completed Code

<?php

// configuration
include 'config.php';

$start = 0;$rowperpage = 3;
if(isset($_POST['start'])){
   $start = mysqli_real_escape_string($con,$_POST['start']); 
}
if(isset($_POST['rowperpage'])){
   $rowperpage = mysqli_real_escape_string($con,$_POST['rowperpage']); 
}

// selecting posts
$query = 'SELECT * FROM posts limit '.$start.','.$rowperpage;

$result = mysqli_query($con,$query);

$html = '';

while($row = mysqli_fetch_array($result)){
   $id = $row['id'];
   $title = $row['title'];
   $content = $row['description'];
   $shortcontent = substr($content, 0, 160)."...";
   $link = $row['link'];

   // Creating HTML structure
   $html .= '<div id="post_'.$id.'" class="post">';
   $html .= '<h2>'.$title.'</h2>';
   $html .= '<p>'.$shortcontent.'</p>';
   $html .= "<a href='".$link."' target='_blank' class='more'>More</a>";
   $html .= '</div>';

}

echo $html;

5. CSS

.container{
  width: 55%;
  margin: 0 auto;
  border: 0px solid black;
  padding: 10px 0px;
}

/* post */
.post{
  width: 97%;
  min-height: 200px;
  padding: 5px;
  border: 1px solid gray;
  margin-bottom: 15px;
}

.post h2{
  letter-spacing: 1px;
  font-weight: normal;
  font-family: sans-serif;
}


.post p{
  letter-spacing: 1px;
  text-overflow: ellipsis;
  line-height: 25px;
}

/* more link */
.more{
  color: blue;
  text-decoration: none;
  letter-spacing: 1px;
  font-size: 16px;
}

6. jQuery

Create 2 functions –

  • checkWindowSize() – Using this function to check if the screen is too large or the page has not had enough content to scroll. If the condition is true then fetch new records by calling fetchData() function.
  • fetchData() – Read values from hidden fields. Fetch new records if start <= allcount.

Send AJAX request to ajaxfile.php, send start as data, and on successful callback append new fetched data responseafter last <div class='post '>. Again check window size by calling checkWindowSize().

scroll event – Check if scroll reaches the bottom of the page or not. If reached then call fetchData().

For mobile-defined touchmove event to detect scrolling.

Completed Code

checkWindowSize();

// Check if the page has enough content or not. If not then fetch records
function checkWindowSize(){
   if($(window).height() >= $(document).height()){
      // Fetch records
      fetchData();
   }
}

// Fetch records
function fetchData(){
   var start = Number($('#start').val());
   var allcount = Number($('#totalrecords').val());
   var rowperpage = Number($('#rowperpage').val());
   start = start + rowperpage;

   if(start <= allcount){
      $('#start').val(start);

      $.ajax({
         url:"ajaxfile.php",
         type: 'post',
         data: {start:start,rowperpage: rowperpage},
         success: function(response){

            // Add
            $(".post:last").after(response).show().fadeIn("slow");

            // Check if the page has enough content or not. If not then fetch records
            checkWindowSize();
         }
      });
   }
}
$(document).on('touchmove', onScroll); // for mobile
       
function onScroll(){
     var position = $(window).scrollTop();
     var bottom = $(document).height() - $(window).height();

     if(position >= bottom) {
          fetchData();
     }
}

$(window).scroll(function(){
     onScroll();
});

7. Demo

View Demo


8. Conclusion

This is another type of pagination where the user doesn’t have to press any key or a button to load new content.

It will automatically load up content whenever the user reaches the bottom of the web page while the page scroll.

If you found this tutorial helpful then don't forget to share.