Infinite Scrolling

Infinite scrolling is a very popular way to replace traditional pagination. Although I believe it is not the best solution for every situation, especially social media made it very popular, just go on Pinterest, Facebook or google plus. so, how can we do it? good you asked. let’s go.

In most cases we will get the contents from a database, so let’s create a connection to the database:

try {
	$conn = new PDO("mysql:host=localhost;dbname=infinitescroll","","");
	
} catch (Exception $e) {
	die("Error " . $e->getMessage());
}

 Obviously, you should include your credentials (username and password).

Next stage: let’s create a query to get the first two records , this is what will be displayed when the page loads:

//make a query to show only the first 2 comments and show it on page
$getthefirstresults = $conn->query("SELECT * FROM comments ORDER BY id LIMIT 0,2");

 We also need the total number of records in the database, so we will be able to calculate later when to create another ajax call:

//get the total amount
$gettotal = $conn->query("SELECT * FROM comments");
$total = $gettotal->rowCount();

 Now we will display the first two records:

<div  class="row">
<ul id="thecomments" class="<?php echo $total; ?>">
<?php

foreach ($getthefirstresults as $key => $value) {?>
		<li>
		<div id="1" class="comment-wrapper">
			<span class="comauth"><?php echo $value['comment_author']; ?></span>
			<p>
				<?php echo $value['comment']; ?>
			</p>
		</div>
	</li>
	<hr>
	<?php
}
?>


</ul>


</div>

 Notice that we echo the total variable. this is how later we will pass it to the ajax call.

So, this is what we have at this point:

first two records

Next, we come to the main idea here. We need to detect when the user scroll down to the end of the page, and when he do, we should make an ajax call to get the next two records from the database:

	var iterator = 0;
	var total =$("#thecomments").attr("class");
	//alert(total);
	$(window).scroll(function(){
		if ($(window).scrollTop() == $(document).height() - $(window).height()) {
			//alert("got to bottom");

			iterator++;
			if (iterator*2 > total) {
				$('#loader').prepend("<p class=' center-text' >no more content !!</p>");
			}else{
				$.ajax({
					type: "POST",
			        //dataType: 'json',
			        url: "getnext.php",
			        data: { 
			        	iterator : iterator
			        },  
			        success: function(data){
			            $("#thecomments").append(data);
			            $("#thecomments li").fadeIn( "slow" );
			        },
			            beforeSend: function () {
			            $("#loader").css({"display": "block"}); 
			            $('#loader').prepend("<p class='loadit center-text' ></p>");
			        },
			        complete: function () {
			        	$("#loader").css({"display": "none"}); 
			           $("p.loadit").fadeOut();
			       }
			   });

			}

		};
	});

 Several things to notice here:

one, we have the variable for the total number of records.

two, we send the iterator variable to the php script, to help us calculate the amount we have and need.

three, the if statement detect when the user scrolled and reached the bottom of the page.

If the call is successful we append the new data and display it. In addition we use the beforesend and complete to display a visual indicator that the call has started and ended.

Now to the php code. It is really simple. We make a query to return the next two records. We use the iterator and multiply it to make a variable to be used in the query. That variable tell us from what number to start to get the next two records:

require_once 'conn.php';
$iterator = $_POST['iterator']*2;
//var_dump($iterator);


//make a query to show the next 2 comments
$getthenextresults = $conn->query("SELECT * FROM comments ORDER BY id LIMIT $iterator,2");
//var_dump($getthenextresults);

foreach ($getthenextresults as $key => $value) {
	?>
	<li>
		<div id="<?php echo $value['id'] ?>" class="comment-wrapper">
			<span class="comauth"><?php echo $value['comment_author'] ?></span>
			<p>
				<?php echo $value['comment'] ?>
			</p>
		</div>
	</li>	
	<hr>
	<?php
}

 This is how it looks when the visual indicator is up, and the results, with the next two records.

visual indicator

results

And that is all. Now whenever the user scroll down a new ajax call will be made and return the next two records until there will be no more records.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.