Load Data Dynamically on Page Scroll using jQuery and PHP

scroll page load data

In this tutorial, we are going to see about loading data into a web page dynamically as the user scrolls it. We will be using jQuery and AJAX for the dynamic load on the scroll. Initially, we will show a limited number of results on page load. The subsequent bunch of records will be shown while scrolling down the page using jQuery AJAX event handler. This is an alternate solution for per-page navigation scenario.

scroll page load data

jQuery AJAX Scroll Down Event Handler

AJAX Function

As the user keeps scrolling, the AJAX call will be continuously invoked until data reaches the end of the record in the database. Following is the AJAX function that shows the loading icon and retrieves data from the backend and shows it.

<script>

  function getresult(url) {
    $.ajax({
      url: url,
      type: "GET",
      data:  {rowcount:$("#rowcount").val()},
      beforeSend: function(){
      $('#loader-icon').show();
      },
      complete: function(){
      $('#loader-icon').hide();
      },
      success: function(data){
      $("#faq-result").append(data);
      },
      error: function(){} 	        
     });
  }
</script>

 

Javascript Event Handler

For loading subsequent record set, we have to know whether the scrollbar reached the bottom of the window. The following Javascript event handler will check if the scroll has reached the bottom and if it reaches then it will fire the AJAX call.

$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".pagenum:last").val() <= $(".rowcount").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
getresult('getresult.php?page='+pagenum);
}
}
});

PHP Page (getresult.php)

PHP page requested by the AJAX scroll event handler is,

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$perPage = 10;

$sql = "SELECT * from user_details";
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}

$start = ($page-1)*$perPage;
if($start < 0) $start = 0;

$query =  $sql . " limit " . $start . "," . $perPage; 
$faq = $db_handle->runQuery($query);

if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
}
$pages  = ceil($_GET["rowcount"]/$perPage);
$output = '';
if(!empty($faq)) {
$output .= '<input type="hidden" class="pagenum" value="' . $page . '" /><input type="hidden" class="total-page" value="' . $pages . '" />';
foreach($faq as $k=>$v) {
 $output .=  '<div class="question">' . $faq[$k]["c_name"] . '</div>';
 $output .= '<div class="answer">' . $faq[$k]["c_address"] . '</div>';
}
}
print $output;
?>

We are familiar with the above PHP script which we have already seen in jQuery pagination tutorial. Presently this PHP script returns 10 records for each scroll event since we have set it as the per-page limit.

Database Config Page (dbcontroller.php)

<?php
class DBController {
  private $host = "localhost";
  private $user = "root";
  private $password = "";
  private $database = "database";
  
  function __construct() {
    $conn = $this->connectDB();
    if(!empty($conn)) {
      $this->selectDB($conn);
    }
  }
  
  function connectDB() {
    $conn = mysql_connect($this->host,$this->user,$this->password);
    return $conn;
  }
  
  function selectDB($conn) {
    mysql_select_db($this->database,$conn);
  }
  
  function runQuery($query) {
    $result = mysql_query($query);
    while($row=mysql_fetch_assoc($result)) {
      $resultset[] = $row;
    }		
    if(!empty($resultset))
      return $resultset;
  }
  
  function numRows($query) {
    $result  = mysql_query($query);
    $rowcount = mysql_num_rows($result);
    return $rowcount;	
  }
}
?>

Full Code  ( Create index.php page )

<HTML>
<HEAD>
<TITLE>Load Data Dynamically on Page Scroll using jQuery AJAX and PHP</TITLE>
<style>
.question {font-weight:bold;background-color:#FFF;padding:7px 0px  0px 15px;}
.answer{font-style:italic;background-color:#FFF;padding:0px 0px 7px 15px;}
#faq-result{margin: -10px auto 0px;width:50%;line-height:30px;border-radius:5px;min-height:300px;}
#loader-icon {position: fixed;top: 50%;width:100%;height:100%;text-align:center;display:none;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.2.6.pack.js"></script>
<script>
$(document).ready(function(){
  function getresult(url) {
    $.ajax({
      url: url,
      type: "GET",
      data:  {rowcount:$("#rowcount").val()},
      beforeSend: function(){
      $('#loader-icon').show();
      },
      complete: function(){
      $('#loader-icon').hide();
      },
      success: function(data){
      $("#faq-result").append(data);
      },
      error: function(){} 	        
     });
  }
  $(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height()){
      if($(".pagenum:last").val() <= $(".total-page").val()) {
        var pagenum = parseInt($(".pagenum:last").val()) + 1;
        getresult('getresult.php?page='+pagenum);
      }
    }
  }); 
});
</script>
</HEAD>
<BODY>
<div id="faq-result">
<?php include('getresult.php'); ?>
</div>
<div id="loader-icon"><img src="LoaderIcon.gif" /><div>
</BODY>
</HTML>

and now create dbcontroller.php and getresult.php .

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – we are here to solve your problems.

 

 

 

Please follow and like us:

By Rodney

I’m Rodney D Clary, a web developer. If you want to start a project and do a quick launch,I am available for freelance work.

Leave a Reply