Load Data While Scrolling Down With jQuery & PHP


If your site have a lot of data to display on a page, it will make the page laggy. With this tutorial, you can limit the data on the main page and load new data when user reach the bottom of the page. This makes it easy to show huge data in a single page.

Before user reaches the end of page.
Before user reaches the end of page.
 
After user reaches the end of page.
After user reaches the end of page.

jQuery will trigger a POST request when user reaches the end of the page. The return data of the request contains the data older than the last data at the time of the trigger. In Server Side (PHP), we’ll use a SQL query that loads data less than the last data Id.

Database Table

You need a table that contains the data with a unique ID. The unique Id can be accomplished using the Auto Increment option of the field with Primary Key option. Here is a sample which we will use throughout this tutorial :

CREATE TABLE data(
 id INT PRIMARY KEY AUTO_INCREMENT,
 data TEXT
);

home.php

The file where the first latest added 10 datas are shown. When user scrolls to the bottom, the next 10 data are shown.

<html>
 <head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
 </head>
 <body>
  <?
  $sql=$dbh->prepare("SELECT * FROM data ORDER BY id DESC LIMIT 10");
  $sql->execute();
  while($r=$sql->fetch()){
   $id=$r['id'];
   $data=$r['data'];
  ?>
   <div id="<?echo $id;?>" class="data">
    <?echo $data;?>
   </div>
  <?
  }
  ?>
  <div class='load_more_data'>
   <div class='normal'>Load More Data</div>
   <div class='loader'>
    <img src='load.gif' height='32' width='32'/>
    <span>Loading More Data</span>
   </div>
  </div>
 </body>
</html>

jQuery

The following jQuery code will call the loadData() function when the “Load More Data” button is clicked or when the user reaches the end of the page. The loadData() function will send the request to the load_data.php file and appends the return HTML data after the last data.

localStorage['dataRequested']=0;
function loadData(){
 var lastDataId=$(".data:last").attr("id");
 var params={};
 params["id"]=lastDataId;
 var t=$(".load_more_data");
 t.find(".normal").hide();
 t.find(".loader").show();
 if(localStorage['dataRequested']==0){
  localStorage['dataRequested']=1;
  $.post("load_data.php", params, function(data){
   if(data!=""){
    $(".data:last").after(data);
   }
   t.find(".normal").show();
   t.find(".loader").hide();
   localStorage['dataRequested']=0;
  });
 }
}
$(document).ready(function(){
 $(".load_more_data .normal").on("click", function(){
  loadData();
 });
 $(window).scroll(function(){
  if($(window).scrollTop() + $(window).height() == $(document).height() && $(".data").length!=0){
   loadData();
  }
 });
});

You can include the above JS code inside a script tag or include it externally via