Facebook Load More Data on Scroll

As most of us have experienced with Facebook, a today-very-popular social network in the world, uses the very user-friendly and most practical features for their social network web system. This tutorial will take a feature, load more data on scroll, which allow users to be able to see more data by just scrolling down. Most of web systems use this feature to display the huge data content or data list with the specific amount of data per scrolling. Doing this will help their website system load data smoothly avoiding of load all data at the first page load.

INSTRUCTION

MySQL Database

CREATE TABLE IF NOT EXISTS `tblusers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(200) NOT NULL,
  `password` varchar(500) NOT NULL,
  `fullname` varchar(200) CHARACTER SET utf8 NOT NULL,
  `nationality` varchar(200) NOT NULL,
  `country` varchar(60) NOT NULL,
  `contactNumber` varchar(200) NOT NULL,
  `email` varchar(60) NOT NULL,  
  `registerDate` datetime NOT NULL,  
  `ative` int(1)NOT NULL  DEFAULT `1`,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `tbluserlog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) NOT NULL,
  `activity` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `dateTime` datetime NOT NULL,
  `active` int(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In this tutorial, we need two database tables to store the user activity log and basic user information.

  • tblusers
  • tbluserlog

These tables contain only the basic information, so we can add more information according to what we really want. However, let’s take these basic database tables for this tutorial.

Javascript File (functions.js)

var customerLogIsLoading = false;
var logStartRecord = 15;
var logRecordPerLoad=15;
		
$(document).ready(function(){
$("#userLog_box").scroll(function(){
if($("#userLog_box").scrollTop() + $("#userLog_box").height()  > $("#userLog_box")[0].scrollHeight-2) {
if(customerLogIsLoading==false){
customerLogIsLoading=true;							
if($('#logLoadingMsg').length){$("#logLoadingMsg").remove();}
$("#userLog_box").append('<div id="cus_loadingGif" style=" text-align:center; font-size:10px; background:url(images/loading_fb.gif) center top no-repeat; height:20px;"></div>');		
$.post("includes/getData.php",{logStartRecord:logStartRecord,logRecordPerLoad:logRecordPerLoad} ,function(data){
$("#cus_loadingGif").remove();
if(data==''){data='<div id="logLoadingMsg" style="text-align:center; font-size:10px;">No More</div>'}
$("#userLog_box").append(data);
logStartRecord+=logRecordPerLoad;	
customerLogIsLoading=false;			
});
}
}
});
});

In the JavaScript file, we have three main variables:

  • customerLogIsLoading: Boolean Data type used for identify whether or not the loading is still in process. 
  • logStartRecord: stores the starting record index to be loaded from the database
  • logRecordPerLoad: stores the number of record to be loaded per scroll event from the database

Actually, we can create a function for all the script in the scroll event if needed. But let’s put the script directly in the scroll event and let’s see how it works.

There are two main functions or events needed for making it works:

  • $(document).ready(): this built-in jQuery function is used to wait until the html and external scripts are completely loaded to the web page before running the custom functions or scripts.
  • $("#userLog_box").scroll(): this jQuery event is used to detect the mouse scrolling event to run the custom functions or scripts.

Now we have all necessary supporting functions or scripts included. The process starts by the follow stages:

  1. Run the Ajax jQuery data request of there is no pending request using variable customerLogIsLoading
  2. Checking if the use scrolled to the bottom of the list to load more data
  3. Check if div element for message exists, then remove it.
  4. Displaying a loading indicator like using text “loading…” or gif animating image
  5. Start Ajax jQuery request by sending data: logStartRecord and logRecordPerLoad
  6. On Ajax success, remove loading element and if there no data return, add a text “No More”
  7. Then append the returned data (can be blank if no data) to the main log element (userLog_box)
  8. Finally, update the variable logStartRecord by make new starting record index and set customerLogIsLoading to false.

PHP File (getData.php)

$dbhost = "localhost";
$dbuser = "khcoder";
$dbpass = "khcoder***";
$dbname = "khcoder";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($conn));

$logStartRecord=$_POST["logStartRecord"];$logBox='';
$logRecordPerLoad=$_POST["logRecordPerLoad"];				
		
$limitRecord=' ORDER BY id DESC LIMIT '.$logStartRecord.','.$logRecordPerLoad;
$log_qry = exec_query_utf8("SELECT * FROM tbluserlog WHERE status=1 ".$limitRecord);
while($row_log = mysqli_fetch_assoc($log_qry)){
$customerName = '';
$customer_qry = exec_query_utf8("SELECT * FROM tblusers WHERE id=".$row_log['userid']." ORDER BY id desc LIMIT 1");
while($row_customer=mysqli_fetch_assoc($customer_qry)){$customerName=$row_customer['fullname'];}					
$logText= '<strong>'.$customerName.'</strong> '.$row_log['activity'];$logDatetime=gmdate("d/m/Y H:i:s",strtotime($row_log['dateTime']));			
$logBox.='<div class="notif_box"><div class="notif_text">'.$logText.'</div><div style=" height:0px;"><div class="notif_datetime">'.$logDatetime.'</div></div></div>';
}
echo $logBox;

In this section, to do the data query, we need to have the database connection by doing the connection configuration. However, we recommend using MySQL UTF8 Connection Using PHP, a useful function for query the UTF8 data.

Then, the above PHP script queries the log data using the provided criteria to limit the number of record to be loaded and the starting record index to be loaded. The data gotten from the query is stored in the variable logText in the html format to match what layout style we want to display in the webpage and then return it to the Ajax function.

HTML Script

<div id=" userLog_box " style="height:400px; overflow-y:scroll; overflow-x:hidden;"></div>

This is the html element used as the block cover for the log data to be loaded. That’s it! Hope it may be helpful!

Similar Tutorials

Comments