A Tutorial on How to Integrate Infinite Scroll with CakePHP

in CakePHP/Tutorials & Samples/Web Development

to-infinity-adn-beyond

I recently had a project that involved integrating infinite scroll, also known as lazy scroll with CakePHP. I also got a private e-mail from one of my readers asking how to do this. So, after my integration was finished, I decided to write a short tutorial on how to integrate infinite scroll with CakePHP. As usual, the entire tutorial can be downloaded here. And as a bonus, I have also setup a demo page of infinite scroll and CakePHP that can be viewed here. When you’re done, you’ll be able to integrate Infinite Scroll with CakePHP like a boss!!!

The Tutorial: A Star Wars Blog With Infinite Scoll

The tutorial is based on CakePHP’s blog tutorial from the bakery. I basically have a blog containing 10 posts about Star Wars. The posts were copied directly from Wikipedia to keep things simple. I then use CakePHP’s paginator to load 2 posts at a time. You can view a demo of the tutorial here. The tutorial includes regular pagination as well as infinite scrolling. I also include the SQL queries to create the posts table and populate it with the Star Wars articles.

Step 1: Download the Infinite Scroll JavaScripts

The first thing you need to do is download the JavaScript library that will be handling the infinite scrolling. For this tutorial, I used the Infinite Scroll Plugin from Paul Irish. It is one of the most popular infinite scroll libraries out there because it is well documented and very easy to integrate. Once you have download the library, you can place it in your webroot/js folder along with a copy of the jQuery library. The plugin requires jQuery so you can either use a local version of jQuery or a version from the CDN. You will have to modify your layout files to include both JavaScript files in order for infinite scroll to work.

Step 2: Download a Spinner image

For you to have the proper effect of infinite scroll, you need to find a proper spinner animation. Our buddy Google has plenty of spinners to choose from. In the end I ended up with this spinner image: Spinner for infinite scroll.

Step 3: Modify your CakePHP view to handle infinite scroll

This tutorial assumes that you are familiar with the Model/View/Controller interaction of CakePHP so we will skip anything related to the setup of the model and the controller. Instead, we will focus on the view. In particular the view responsible for the infinite scrolling. The file in particular is index.ctp locate in View/Posts/index.ctp. The view is separated into 3 sections:

  1. The Main Section to Display Blog Posts
  2. The Pagination Element
  3. The Infinite Scroll Javascript

Step 3A: Modify The Main Section to Display Blog Posts

This is the main section responsible for showing your content. You must have a div element to indicate the container for each one of your individual posts. In my case, I have a div element called posts-list. You must also have a defined class name for each of the individual posts. In my case, I have a div element that wraps each element called post-item. You can look at the div with id posts-list as the main container and the post-item class as the container for each individual post. The infinite scroll library needs to know the id of these 2 elements in order to dynamically modify the content as the user scrolls down the page. The following is the code..

		<div id="posts-list" class="grid_entry row masonry" style="width:50%" > 
		
			<?php foreach($posts as $post){ ?>
			<div class="post-item">
				<h2><?php echo $this->Html->link($post['Post']['title'],
	array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?></h2>
				<p><?php echo $post['Post']['body']; ?></p>
				<p><?php echo $post['Post']['created']; ?></p>
				<hr/>
			</div>
			<?php } ?>
		</div>

Step 3B: Modify The Pagination Element

CakePHP allows you to create the pagination link using the function Paginator->next(). This function will create a link to the next set of posts to load. You do not have to change anything with this call. The infinite scroll library will dynamically call this link and append its content to the posts-list element. The following is the pagination code..

<?php
		echo $this->Paginator->next('Show more star wars posts...');
?>

Step 3C: Modify The Infinite Scroll Javascript

You need to modify your infinite scroll javascript to specify the DIV element names that you used in step 3A. So in my case, I specify that my itemSelector element is called .post-item and that my main container is called #posts-list. Since this is a tutorial, I also enable the debug flag so that any errors can be displayed in the console. Finally, I setup the message to display when all paging has finished and the location of my spinner.gif image that was download in Step 2.

<script>
  $(function(){
	var $container = $('#posts-list');

	$container.infinitescroll({
	  navSelector  : '.next',    // selector for the paged navigation 
	  nextSelector : '.next a',  // selector for the NEXT link (to page 2)
	  itemSelector : '.post-item',     // selector for all items you'll retrieve
	  debug		 	: true,
	  dataType	 	: 'html',
	  loading: {
		  finishedMsg: 'No more posts to load. All Hail Star Wars God!',
		  img: '<?php echo $this->webroot; ?>img/spinner.gif'
		}
	  }
	);
  });

</script>

You’re Done

That’s it! You’re done integrating infinite scroll with CakePHP! Don’t forget to modify your layout file so that you load the javascript files. In my case, I modified the default CakePHP layout to load jQuery and the infinite scroll library. That’s it. You’re now a infinite scroll with CakePHP Jedi. The entire tutorial can be downloaded here and you can view the demo page here. If you have any comments or issues, hit me up in the comments section…

Tags:

Mifty Yusuf is a Montreal-based software developer who enjoys playing with new web technologies as well as comic books and illustrations. He beleives that, no matter what the question is, the answer is always Batman!

13 Comments

  1. hi,
    thanks for such a nice tutorial. I had implement within a minute.
    But i want to set the position of spinner image, messages at center of line.
    How can do this?
    where should i change in your script?

  2. There is something going wrong in your code , it seems that it si showing for me the same results for each loaded page … in the example you provided it worked for you because the text of each posts is too long to display. I followed your example using RSS Request in CakePHP … when i scroll down , the page loading animation work perfectelly but the same loaded results are loaded again and again each time i scroll …

  3. Can you please describe …how to use this auto scrolling with Caching ..like File,Redis..cause caching find very easy but and caching paginated items are also possible but auto scrolled items ?? how to cache them ?

  4. Hello, it is very useful tutorial. But I am confused with the javascript piece of code you posted. I am following exactly what you have written but not able to fine the code to change the div id of post-list and post-item. Can you please guide me on this? I am using this auto load in the comments list where a post contains the comments. Relation is “Post has many comments” and comment list is in the PostsController->view action.

    I can explain more if you need.

  5. I am using this auto load in the comments list where a post contains the comments.
    Relation is “Post has many comments” and comment list is in the PostsController->view action. Posts/view.ctp has the post title, description and comments list. If I scroll down the list of comments it gets reload the same comments again and again. What is the solution?

  6. Any idea why this breaks the CSS style sheet? when i use it? all i get is text and the style sheet doest seem to work now?
    im using cakephp 3.4 btw

Leave a Reply

Your email address will not be published.

*

Latest from CakePHP

Go to Top