Facebook Like Infinite Scroll Using jQuery Ajax PHP and MySQL

Posted by & filed under Ajax, CSS, HTML5, JQUERY, MYSQL, PHP.

In previous tutorial we have seen how to implement Infinite Scroll using jQuery, but in this tutorial we are going to implement this Facebook Like Infinite Scroll using jQuery Ajax PHP and MySQL. Here we are going to make Ajax request to server if user wants to see more data.

I have implemented this Infinite scrolling in two ways.

  1.  One way is making Ajax request to server and getting response as json formatted data, and do the all process on the client side.
  2.  Second way is making Ajax request to server and getting data from the database, and with the data we form HTML on the server side itself. Finally server send response as HTML processed data.

In the second approach we do all the process on the server itself. If the number visitor going to increase to your site, then doing all the process on server side bad idea. It increases your operating cost of the services, so it best do the most of the process in client side, that will cut your operating cost of your business.

Please refer following two tutorial before continuing this tutorial.

Responsive Facebook Style Timeline Design With Twitter Bootstrap

Facebook Like Infinite Scroll Using jQuery

 

 

Facebook Like Infinite Scroll Using jQuery Ajax PHP and MySQL

Create index.php file and add basic HTML markup in it.

Create a directory called infinite-scroll in your htdocs or in your server root folder. Now add create following list of folders (css, js ) in the infinite-scroll directory. Then download bootstrap and jQuery files and add in their respective css and js directories. Now create index.php file and include those css and js files in index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Infinite Scroll</title>
	<!-- Bootstrap -->
	<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,200' rel='stylesheet' type='text/css'>	
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
	<link href="css/style.css" rel="stylesheet">

	<!-- Script -->
	<script src="js/jquery.min.js"></script>
	<script src="js/bootstrap.min.js"></script>
	<script src="js/script.js"> </script>
</head>
<body>

 

 

Facebook Timeline Design and jQuery Infinite Scroll:

We have seen both this Facebook Timeline Design and jQuery Infinite Scroll in the previous tutorials. So please refer both this tutorials.

Responsive Facebook Style Timeline Design With Twitter Bootstrap

Facebook Like Infinite Scroll Using jQuery

jQuery Infinite Scroll Ajax Request:

When the total document height will equal to the window height plus total scroll height, then following script will automatically makes Ajax request to get data from the server.

I am keeping flag that prevents making multiple Ajax request at the same time with same parameters. Every time we make Ajax request we need to pass minimum of two parameters that are limit to MySQL queries ( where to start and how many records it needs to fetched.) . I am keeping those two values in HTML hidden fields like this in index.php file.

<input type="hidden" id="first" value="<?php echo FIRST; ?>" />
<input type="hidden" id="limit" value="<?php echo LIMIT; ?>" >

While I am making Ajax request, i am getting those two hidden values

first = $('#first').val();
limit = $('#limit').val();

and passing those two values to the server.

data: {
     start : first,
     limit : limit
}

Whenever you got response from the server, then I am incrementing the limit value to get next set of values from the server.

first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val( first+limit );

Here is the full Ajax request script.

flag = true;
$(window).scroll(function() {
	if($(window).scrollTop() + $(window).height() == $(document).height()){
		first = $('#first').val();
		limit = $('#limit').val();
		no_data = true;
		if(flag && no_data){
			flag = false;
			$('#loader').show();
			$.ajax({
				url : 'ajax.php',
				dataType: "json",
				method: 'post',
				data: {
				   start : first,
				   limit : limit
				},
				success: function( data ) {
					flag = true;
					$('#loader').hide();
					if(data.count > 0 ){
						first = parseInt($('#first').val());
						limit = parseInt($('#limit').val());
						$('#first').val( first+limit );
						$('#timeline-conatiner').append( '<li class="year">'+year+'</li>');
						$.each(data.content, function(key, value ){
							html = '<li class="event">';
							html += '<h3 class="heading">'+value.name+'</h3>';
							html += '<span class="month"><i class="fa fa-calendar"></i>'+value.name+'</span><p>&nbsp;</p>';
							html += '<p><a href="'+value.demo+'" target="_blank">Demo </a></p>';
							html += '<p><a href="'+value.tutorial+'" target="_blank">Tutorial </a></p>';
							
							if(value.media_type == 'video' && value.media !=''){
								html += '<div class="embed-responsive embed-responsive-16by9">';
								html += '<iframe frameborder="0" allowfullscreen="allowfullscreen" src="'+value.media+'" class="embed-responsive-item"></iframe>';
								html += '</div>';
							}
							if(value.media_type == 'image' && value.media !='' ){
								html += '<div class="text-center">';
								html += '<img class="img-responsive img-thumbnail" src="'+value.media+'">';
								html += '</div>';
							}
							html += '<p>'+value.description+'</p>';
							html += '</li>';
							$('#timeline-conatiner').append( html );
						});
						year--;
					}else{
						alert('No more data to show');
						no_data = false;
					}
				},
				error: function( data ){
					flag = true;
					$('#loader').hide();
					no_data = false;
					alert('Something went wrong, Please contact admin');
				}
			});
		}
		
		
	}
});	
	

Here I am getting json response from the server, then using jQuery $.each() statement I am forming the HTML and append it to the timeline design.

Handle Infinite Scroll Ajax Request Using PHP

Create timeline table using following SQL Queries.

CREATE TABLE IF NOT EXISTS `timeline` (
`id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `description` text NOT NULL,
  `media` varchar(250) NOT NULL,
  `media_type` enum('video','image') NOT NULL,
  `demo` varchar(300) NOT NULL,
  `tutorial` varchar(300) NOT NULL,
  `created` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=370 DEFAULT CHARSET=latin1;

Now create config.php file to keep database configuration.

<?php
/*
Site : http:www.smarttutorials.net
Author :muni
*/
//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/timeline/');
define('DB_HOST', 'localhost');
define('DB_NAME', 'timeline');
define('DB_USERNAME','root');
define('DB_PASSWORD',''); 

$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();


define('FIRST', 4);
define('LIMIT', 4);

Now create ajax.php file that handles the Ajax request and sends the response to the client. Here ajax.php file PHP script.

<?php
require_once 'config.php';

if( isset( $_POST['start'] ) && isset( $_POST['limit'] ) && !empty( $_POST['start'] ) && !empty( $_POST['limit'] ) ){
	$start = $_POST['start'];
	$limit = $_POST['limit'];
	$query = "SELECT * FROM timeline limit $start, $limit";
	$result = mysqli_query($con, $query) or die('Error: ' . mysqli_error($con));
	$data = array();
	$rowcount = mysqli_num_rows($result);
	$data['count'] = $rowcount;
	while($row = mysqli_fetch_assoc($result)) {
		$data['content'][] = $row;
	}
	mysqli_close($con);
	echo json_encode($data);exit;	
}

Here is the second method of Infinite Scroll Using jQuery Ajax PHP and MySQL

 

 

Here is the jQuery script that makes Ajax request to the server, and then just appends the response from the server directly to the timeline design.

flag = true;
$(window).scroll(function() {
	if($(window).scrollTop() + $(window).height() == $(document).height()){
		first = $('#first').val();
		limit = $('#limit').val();
		no_data = true;
		if(flag && no_data){
			flag = false;
			$('#loader').show();
			$.ajax({
				url : 'ajax_html.php',
				method: 'post',
				data: {
				   start : first,
				   limit : limit
				},
				success: function( data ) {
					flag = true;
					$('#loader').hide();
					if(data !=''){
						
						first = parseInt($('#first').val());
						limit = parseInt($('#limit').val());
						$('#first').val( first+limit );
						$('#timeline-conatiner').append( '<li class="year">'+year+'</li>');
						
						$('#timeline-conatiner').append( data );
						year--;
					}else{
						alert('No more data to show');
						no_data = false;
					}
				},
				error: function( data ){
					flag = true;
					$('#loader').hide();
					no_data = false;
					alert('Something went wrong, Please contact admin');
				}
			});
		}
		
		
	}
});	

You see in the above script we are not doing anything just appends the response from the server.

Here is the PHP Script that’s forms the HTML on the server side itself, and finally send the response to the client.

<?php
require_once 'config.php';

if( isset( $_POST['start'] ) && isset( $_POST['limit'] ) && !empty( $_POST['start'] ) && !empty( $_POST['limit'] ) ){
	$start = $_POST['start'];
	$limit = $_POST['limit'];
	$query = "SELECT * FROM timeline limit $start, $limit";
	$result = mysqli_query($con, $query) or die('Error: ' . mysqli_error($con));
	$data = array();
	$rowcount = mysqli_num_rows($result);
	$data['count'] = $rowcount;
	$html = '';
	while($row = mysqli_fetch_assoc($result)) {
		$html .= '<li class="event">';
		$html .= '<h3 class="heading">'.$row['name'].'</h3>';
		$html .= '<span class="month"><i class="fa fa-calendar"></i>'.$row['name'].'</span><p>&nbsp;</p>';
		$html .= '<p><a href="'.$row['demo'].'" target="_blank">Demo </a></p>';
		$html .= '<p><a href="'.$row['tutorial'].'" target="_blank">Tutorial </a></p>';
			
		if($row['media_type'] == 'video' && $row['media'] !=''){
			$html .= '<div class="embed-responsive embed-responsive-16by9">';
			$html .= '<iframe frameborder="0" allowfullscreen="allowfullscreen" src="'.$row['media'].'" class="embed-responsive-item"></iframe>';
			$html .= '</div>';
		}
		if($row['media_type'] == 'image' && $row['media'] !='' ){
			$html .= '<div class="text-center">';
			$html .= '<img class="img-responsive img-thumbnail" src="'.$row['media'].'">';
			$html .= '</div>';
		}
		$html .= '<p>'.$row['description'].'</p>';
		$html .= '</li>';
	}
	mysqli_close($con);
	echo $html;exit;	
}



Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!