Both Twitter and the Apple App Store use a brilliant technique for loading more information; you click the link and fresh items magically appear on the screen. This tutorial teaches you to use AJAX, CSS, Javascript, JSON, PHP, and HTML to create that magic. This tutorial will also feature both jQuery and MooTools versions of the script.
Assumptions
There are a few assumptions and notes that we're going into this system with:
- The server needs to be running PHP5 so that we can use PHP5's JSON functions.
- We'll be pulling database records from a WordPress "posts" MySQL table. What's great about the code provided is that you may use it with any database system; all you'll need to do is modify the MySQL query and the JSON properties used by jQuery or MooTools.
- The client must support javascript.
- We're using MooTools 1.2.3 Core and More 1.2.3.1. If jQuery is the preferred framework, jQuery 1.3.2 and Ariel Flesler's ScrollTo plugin.
This tutorial will feature an explanation of the MooTools javascript. While jQuery's syntax differs from MooTools, the beauty in modern javascript frameworks is that they differ mainly in syntax, not in logic. The jQuery javascript will be provided below.
The Plot
Here's the sequence of events that will take place in our slick widget:
- The page loads normally with an initial amount of posts showing
- The user clicks the "Load More" element at the bottom of the list
- An AJAX/JSON request will fire, retrieving a specified amount of new posts
- Our jQuery/MooTools javascript will receive the result and build a series of new HTML elements containing the JSON's information
- Each element will slide into the widget's container element
- Once all of the elements have been loaded into the page, the window will scroll down to the first new item
- Rinse and repeat.

Step One: The PHP/MySQL
The first step is deciding how many posts need to be loaded during the initial page load. Since our widget will remember how many posts were loaded during the last load (in case a user visits another page and comes back), we'll need to use the session.
/* settings */ session_start(); $number_of_posts = 5; //5 posts will load at a time $_SESSION['posts_start'] = $_SESSION['posts_start'] ? $_SESSION['posts_start'] : $number_of_posts; //where we should start
The above code snippet contains all the "settings" content that we need. Next we need to create a PHP function that connects to our database, grabs more records, and returns their contents in JSON format:
/* grab stuff */
function get_posts($start = 0, $number_of_posts = 5) {
/* connect to and select the db */
$connection = mysql_connect('localhost','username','password'); //hostname, username, password
mysql_select_db('davidwalsh83_blog',$connection);
/* create the posts array */
$posts = array();
/* get the posts */
$query = "SELECT post_title, post_content, post_name, ID FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT $start,$number_of_posts";
$result = mysql_query($query);
/* for every post... */
while($row = mysql_fetch_assoc($result)) {
/* set the post content equal to the first paragraph...a "preview" regular expression */
preg_match("/<p>(.*)<\/p>/",$row['post_content'],$matches);
$row['post_content'] = strip_tags($matches[1]);
/* add this record to the posts array */
$posts[] = $row;
}
/* return the posts in the JSON format */
return json_encode($posts);
}
The above PHP contains a very simple regular expression that grabs the first paragraph of my post's content. Since the first paragraph of most blog posts serves as a introduction to the rest of the content, we can assume that paragraph will server as a nice preview of the post.
Once the above function is ready, we need to create our AJAX request listener. We'll know that someone has sent an AJAX request if the $_GET['start'] variable is set in the request URL. If a request is sensed, we grab 5 more posts via our get_posts() function and echo their JSON out. Once we've output the new posts in JSON format, we save the number of items that the user has requested and kill the script, as seen below.
/* loading of stuff */
if(isset($_GET['start'])) {
/* spit out the posts within the desired range */
echo get_posts($_GET['start'],$_GET['desiredPosts']);
/* save the user's "spot", so to speak */
$_SESSION['posts_start']+= $_GET['desiredPosts'];
/* kill the page */
die();
}
That concludes the server-side code for our widget. Simple, no?

Step 2: The HTML
There's not much raw HTML to this widget initially. We'll create one main widget container. Inside the widget container will be a posts wrapper and our "Load More" element which will server as a virtual like to trigger the loading of more content.
<!-- Widget HTML Starts Here --> <div id="posts-container"> <!-- Posts go inside this DIV --> <div id="posts"></div> <!-- Load More "Link" --> <div id="load-more">Load More</div> </div> <!-- Widget HTML Ends Here -->
Though we don't insert individual post elements yet, it's important to know the HTML structure of post DIV elements that will be injected into the posts wrapper:
<div class="post">
<a href="{postURL}" class="post-title">{post_title}</a>
<p class="post-content">
{post_content}
<br />
<a href="{postURL}" class="post-more">Read more...</a>
</p>
</div>

Step 3: The CSS
Time to add some flare to our widget. Feel free to format the widget's elements any way you'd like. I've chosen to add my caricature on the left and the post title, content, and link to the right. We'll need to add CSS for the static HTML elements and the javascript-generated elements as show below.
#posts-container { width:400px; border:1px solid #ccc; -webkit-border-radius:10px; -moz-border-radius:10px; }
.post { padding:5px 10px 5px 100px; min-height:65px; border-bottom:1px solid #ccc; background:url(dwloadmore.png) 5px 5px no-repeat; cursor:pointer; }
.post:hover { background-color:lightblue; }
a.post-title { font-weight:bold; font-size:12px; text-decoration:none; }
a.post-title:hover { text-decoration:underline; color:#900; }
a.post-more { color:#900; }
p.post-content { font-size:10px; line-height:17px; padding-bottom:0; }
#load-more { background-color:#eee; color:#999; font-weight:bold; text-align:center; padding:10px 0; cursor:pointer; }
#load-more:hover { color:#666; }
One extra CSS class we'll create is called "activate", which we'll show whenever an AJAX request starts and hide when the request completes.
.activate { background:url(/dw-content/loadmorespinner.gif) 140px 9px no-repeat #eee; }

Step 4: The MooTools Javascript
Our MooTools javascript will make the magic happen. We'll use a closure pattern to contain the MooTools code as a best practice:
//safety closure
(function($) {
//when the DOM is ready...
window.addEvent('domready,function() {
/* ALL JAVASCRIPT WILL BE IN HERE */
});
})(document.id);
Once the DOM is ready, we provide the initial javascript settings. Note that one of those settings, initialPosts, contains the JSON for the first batch of posts that should show when the page loads. We also define variables for how many posts we load initially and the number of posts to grab during each AJAX request.
//settings on top var domain = 'http://davidwalsh.name/'; //your domain or directory path goes here var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>; var start = <php echo $_SESSION['posts_start']; ?>; var desiredPosts = <?php echo $number_of_posts; ?>;

Once our settings are in place, we define a function to handle the JSON we receive at page load as well as via future AJAX requests. For every post in the JSON, we...
- Create a post URL variable which we'll use a bit later in the loop
- Create a DIV "post" element which will contain the post title, content, and link (in the format shown above)
- Inject the newly created "post" element into the posts wrapper
- Create a Fx.Slide object for the new "post" element so we can hide the element instantly, then slide it into view
- Scroll the window down to the first newly-injected post
Here's the MooTools javascript code that gets it done.
//function that creates the posts
var postHandler = function(postsJSON) {
postsJSON.each(function(post,i) {
//post url
var postURL = '' + domain + post.post_name;
//create the HTML "post" element
var postDiv = new Element('div',{
'class': 'post',
events: {
//click event that makes the entire DIV clickable
click: function() {
window.location = postURL;
}
},
id: 'post-' + post.ID,
html: '<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>'
});
//inject into the container
postDiv.inject($('posts'));
//create the Fx Slider
var fx = new Fx.Slide(postDiv).hide().slideIn();
//scroll to first NEW item
if(i == 0) {
var scroll = function() {
new Fx.Scroll(window).toElement($('post-' + post.ID));
};
scroll.delay(300); //give time so scrolling can happen
}
});
};

Now that our postHandler function is defined, it's time to handle the initial JSON string of elements.
//place the initial posts in the page postHandler(initialPosts);
Next we create a few more variables to store the value of our AJAX request and hold the values of the PHP session's start value, the number of posts to grab at a time, and the "Load More" element.
var start = ;
var desiredPosts = ;
var loadMore = $('load-more');
To cut down on memory usage, we'll create our Request.JSON object outside of the click event we'll soon add. The Request.JSON object looks long but it's really quite simple. Breaking it down...
We create the request object with basic settings...
var request = new Request.JSON({
url: 'load-more.php', //ajax script -- same script
method: 'get',
link: 'cancel',
noCache: true,
//more settings coming...
Add an onRequest parameter that adds our "activate" CSS class to the "Load More" clickable element and change the "Load More" element's text to "Loading..."....
onRequest: function() {
//add the activate class and change the message
loadMore.addClass('activate').set('text','Loading...');
},
Add an onSuccess parameter that resets the "Load More" element text, keeps track of the current start spot for grabbing future elements, and handle the JSON response the same way we did with the initial posts...
onSuccess: function(responseJSON) {
//reset the message
loadMore.set('text','Load More');
//increment the current status
start += desiredPosts;
//add in the new posts
postHandler(responseJSON);
},
Add an onFailure function to update the "LoadMore" text upon failure...
onFailure: function() {
//reset the message
loadMore.set('text','Oops! Try Again.');
},
Lastly, add an onComplete function that removes the spinner once the request is complete, regardless of success or failure.
onComplete: function() {
//remove the spinner
loadMore.removeClass('activate');
}
The last step is adding the click event to "Load More" element. Upon click we make the AJAX request and all of the work above gets triggered. Success!
//add the "Load More" click event
loadMore.addEvent('click',function(){
//begin the ajax attempt
request.send({
data: {
'start': start,
'desiredPosts': desiredPosts
},
});
});

MooTools Complete Code
//safety closure
(function($) {
//domready event
window.addEvent('domready',function() {
//settings on top
var domain = 'http://davidwalsh.name/';
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
//function that creates the posts
var postHandler = function(postsJSON) {
postsJSON.each(function(post,i) {
//post url
var postURL = '' + domain + post.post_name;
//create the HTML
var postDiv = new Element('div',{
'class': 'post',
events: {
click: function() {
window.location = postURL;
}
},
id: 'post-' + post.ID,
html: '<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>'
});
//inject into the container
postDiv.inject($('posts'));
//create the Fx Slider
var fx = new Fx.Slide(postDiv).hide().slideIn();
//scroll to first NEW item
if(i == 0) {
var scroll = function() {
new Fx.Scroll(window).toElement($('post-' + post.ID));
};
scroll.delay(300); //give time so scrolling can happen
}
});
};
//place the initial posts in the page
postHandler(initialPosts);
//a few more variables
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('load-more');
var request = new Request.JSON({
url: 'load-more.php', //ajax script -- same page
method: 'get',
link: 'cancel',
noCache: true,
onRequest: function() {
//add the activate class and change the message
loadMore.addClass('activate').set('text','Loading...');
},
onSuccess: function(responseJSON) {
//reset the message
loadMore.set('text','Load More');
//increment the current status
start += desiredPosts;
//add in the new posts
postHandler(responseJSON);
},
onFailure: function() {
//reset the message
loadMore.set('text','Oops! Try Again.');
},
onComplete: function() {
//remove the spinner
loadMore.removeClass('activate');
}
});
//add the "Load More" click event
loadMore.addEvent('click',function(){
//begin the ajax attempt
request.send({
data: {
'start': start,
'desiredPosts': desiredPosts
},
});
});
});
})(document.id);
jQuery Version
If you prefer the jQuery javascript framework, it's your lucky day; here's the jQuery version:
//when the DOM is ready
$(document).ready(function(){
//settings on top
var domain = 'http://davidwalsh.name/';
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
//function that creates posts
var postHandler = function(postsJSON) {
$.each(postsJSON,function(i,post) {
//post url
var postURL = '' + domain + post.post_name;
var id = 'post-' + post.ID;
//create the HTML
$('<div></div>')
.addClass('post')
.attr('id',id)
//generate the HTML
.html('<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>')
.click(function() {
window.location = postURL;
})
//inject into the container
.appendTo($('#posts'))
.hide()
.slideDown(250,function() {
if(i == 0) {
$.scrollTo($('div#' + id));
}
});
});
};
//place the initial posts in the page
postHandler(initialPosts);
//first, take care of the "load more"
//when someone clicks on the "load more" DIV
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
//load event / ajax
loadMore.click(function(){
//add the activate class and change the message
loadMore.addClass('activate').text('Loading...');
//begin the ajax attempt
$.ajax({
url: 'load-more.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function(responseJSON) {
//reset the message
loadMore.text('Load More');
//increment the current status
start += desiredPosts;
//add in the new posts
postHandler(responseJSON);
},
//failure class
error: function() {
//reset the message
loadMore.text('Oops! Try Again.');
},
//complete event
complete: function() {
//remove the spinner
loadMore.removeClass('activate');
}
});
});
});
The MooTools and jQuery versions are exactly the same logic with different syntax!
Mission Accomplished!
Implementing this widget on your website is a great way to add dynamism and creativity to your website. I look forward to seeing your widget! Have questions suggestions for improvements? Post them below!
- Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.












User Comments
( ADD YOURS )crysfel July 16th
It would be better if you create a Class to wrap that code
the mootools framework is awesome working with classes and objects, that is the only thing that i like about mootools
good tutorial BTW.
( )Sass July 16th
Great as always from David.
( )Evan Riley July 16th
The tutorial is absolutely amazing, and it’s great that you made a Mootools version and a jQuery version.
But one question, instead of grabbing the ‘post’ from a MySQL database couldn’t you just grab the feed RSS with SimplePie?
( )Benjamin Reid July 16th
“couldn’t you just grab the feed RSS with SimplePie?”
That would be a great adaption.
( )Evan Riley July 16th
Yea, hopefully, If I just skip the PHP/MySQL part and instead use SimplePie to grab a RSS Feed, and just follow the HTML and JS part’s I can get it to work. Looks like this is going to be my morning project.
Benjamin Reid July 16th
Mind posting any results?
Evan Riley July 16th
Yea I don’t mind posting my results, as long as it doesn’t mess with some CopyRight’s that i’m not seeing :p
Jason July 16th
I wouldn’t mind seeing this work with SimplePie either. I’m thinking it could be a handy way to display forum posts on an iPhone.
Brenda November 14th
@Evan Riley: were you ever able to do this tut with Simplepie? did you post results anywhere?
Mnowluck July 16th
Interesting.. I’m gonna try this out…
( )Benjamin Reid July 16th
Great timing NETTUTS, and David of course! I was looking for this exact TUT. Then I saw Mootools and though ‘Oh no!’ but David’s kindly included the jQuery too, schweet! That might need a little bit of studying though.
The PHP and JavaScript looks really solid. I want to try and implement into my WordPress site. Perhaps to load extra tags, related posts or posts themselves. With a little bit of tweaking of the SQL it should work really well, but the WP database is a little more complicated than the one in the tutorial.
A possible WP plugin here?
( )David Walsh July 16th
@crysfel: In this case, I skipped “class-ifying” it to keep it more flexible for anyone to implement.
@Evan Riley: If it’s not your site, that’s a good idea. Why add another layer of abstraction if it’s your site though?
@Benjamin Reid: A WP plugin would be possible but for the sake of the tutorial I wanted to keep it flexible and not dependent upon WordPress.
( )Evan Riley July 16th
Thanks for the reply David, as for the SimplePie, what I was talking about is using SimplePie to bring in more than one site (rather than just have one site shown). I completely understand your thought about the extra layers, but even then it might be easier for people who are quite new to PHP.
( )Benjamin Reid July 16th
Yeah of course. I might make / adapt it into one. Though with permission from yourself.
( )dhype July 16th
Brilliant, great tutorial
( )Steve July 16th
Is it possible to do the same thing, but instead of adding another 5 entrys on, can you replace the current 5? So there is always only 5 there.
( )ryan July 16th
nice tutorial
( )David Walsh July 16th
@Benjamin Reid: Of course — make it happen!
@Steve: Pretty easily, actually. Inside the “onSuccess” Request event, before adding the items in, empty out the “#posts” element’s HTML.
( )Steve July 17th
Ah wicked, thanks.
( )Jeremy Martin July 16th
Great article David – you’re a writing machine.
*Grotesquely nitpicky suggestion – might make sense to use function closure on the jQuery version as well.
( )Myfacefriends July 16th
this is great my next thing to do is to combined this to smarty so i can use it to my site! thanks.
( )Shane July 16th
Nice technique, good tutorial.
Twitter’s use of the ‘more’ bar can be infuriating if you have clicked it a few times to read more tweets from people you’re following and then navigate away from the page and return. You lose all the additional tweets that you invoked using several clicks of ‘more’.
I guess this could be sorted with some URL fiddling, but it really bugs the hell out of me how it currently stands.
( )David Walsh July 16th
@Shane: Hopefully I’ve saved that frustration!
( )Shane July 16th
Yeah – yours is better than Twitter’s
( )Shane July 16th
Um… sorry for another comment. Twitter seems to have sorted it out!
Jason July 16th
Thanks for the tutorial. Can you add a way to remove the ‘Load More’ button once you’ve retrieved all the posts? Maybe the php would send a specific header and the js would interact with it accordingly?
( )Diego SA July 16th
Every tut from David Walsh is excellent. Always saving my skin! Thanks!
( )mary July 16th
Thanks for this tutorial! Very clear and well explained.
I’m definitely going to try this out on a new project I’m working on. The only thing I would change would be to use prepared statements to connect to and query the database… but that’s just a personal preference on my part
thanks again!!
( )Ahmad Alfy July 16th
David you ROCK
( )I enjoyed your tutorials @ your blog for a long time and I am glad to see you writing for nettuts
David Walsh July 16th
Thanks Ahmad!
( )choen July 16th
It so cool..tutorial, i can choice jquery or mootools.. thanks..
( )Ryan July 16th
She doesn’t work on Internet Explorer (Don’t scream at me – I’m at work)
( )Srinivas Tamada July 16th
Great tutorial… One more like this
” Twitter like more button ”
( )http://9lessons.blogspot.com/2009/04/twitter-like-more-button-with-jquery.html
DaveK July 17th
Nice very handy tutorial.
( )Phil July 17th
The demo doesn’t work in IE7 or IE6. Possibly a misplaced/omitted comma.
I’m not an IE user myself and tend to not cater for 6 anymore, but 7 is surely a must?
( )Yigit Ozdamar July 17th
Great tut!
( )David Walsh July 17th
@Phil: Extra comma. Good to go now!
( )DemoGeek July 17th
I would prefer to have a collapse feature also baked-in as once expanded there is no way to collapse except if you refresh the page.
( )Chris the Developer July 17th
Excellent tutorial – I’m gonna throw it into a class, and add some small things like deep linking, and hiding individual entries (mark as read).
There’s a missing apos. in the very first MooTools snippet (around domready).
( )Styledev October 10th
I would be really interested in your results on this. Also it would be cool to be able to set a show limit and have it loop so you can come back around.
( )Yoosuf July 17th
nice one, i really appricate it
( )Hieu Vo July 17th
Nice effect
( )Robert Visser July 17th
David,
Hi.
Really excellent tutorial, source code, and demo. Great that the rounded corners in the demo are created w/CSS3. Thanks.
I’d like to see this revisited using AJAX/PHP rather than AJAX/JSON requests. Two examples would be particularly beneficial; one where the content loads from an on-page div and one where the content loads from a query to a MySQL database.
The primary concern is indexing the content. I ran the demo page through a bevy of keyword density tools.
Bruce Clay’s Keyword Density Analyzer: http://bit.ly/TWTvm
PageRank-SEO’s Keyword Density Checker: http://bit.ly/wqIwI
SEO Book’s Keyword Density Analyzer Tool: http://bit.ly/rMJLO
SEO Chat’s Keyword Density Checker: http://bit.ly/XauR5
Submit Express’s Meta Tag Analyzer: http://bit.ly/UeDzY
WeBuildPages Keyword Density Analyzer: http://bit.ly/F5GEl
WebConfs’s Keyword Density Checker: http://bit.ly/a89dv
Please note: The links for Bruce Clay’s and SEO Chat’s include the results. For the other tools you have to enter the demo’s URL: http://davidwalsh.name/dw-content/load-more.php . Also, I believe SEO Book and WeBuildPages utilize the same tool, albeit a slightly different CSS layout.
The results from all seven tools indicate content of any of the posts isn’t visible.
Thanks.
Rob
( )Geoserv July 17th
Very nice, I love jQuery. It’s so flexible and the possibilities seem to be endless.
Good tut.
( )Brandon Dove July 17th
David –
This is a great topic and you’ve laid it out nicely with both MooTools and jQuery options.
I worked up a PHP file that your readers can drop right into the WordPress root that uses built in WordPress template tags (so they don’t have to get their hands dirty with SQL). It uses the standard WordPress loop to populate the JSON with a title and the post excerpt. It’s available for download at the url below.
http://www.think-press.com/380/twitter-style-post-loading-in-wordpress/
Thanks again for a great write up!
-Brandon
( )Jaspal Singh July 18th
Great tutorial on how to build your own Twitter like “Load More” widget.
( )Thanks for sharing.
Abu Farhan July 20th
Great tutorial using Json. I want to try this one, can I used for any json source ?
( )tasarhane July 24th
very good tutorial.. thanks
( )hatkim web design July 27th
cool very interesting codes
( )Abe July 31st
This question may be silly, but I don’t understand how your using PHP inside of the jquery script file.
When I do it I just get blanks (I tested some echo’s with alerts). Help please, I’d really like to use this script
( )Stephen Clark August 8th
I agree with Abe. Please help with Abe’s question. I don’t understand where the PHP code connects to the MooTools script.
( )David Walsh August 13th
Abe — you have all of the PHP and javascript in one file, right? Turn on errors so you can see what exactly is happening.
( )Navdeep Singj August 1st
Very much inspired to david blog http://davidwalsh.name/…. that our blog at Zanetine http://blog.zanetine.com and http://zanetinewebdesign.com
( )Miles September 19th
Is there WP plugin for this or did any one manage to implement this into WP?
( )tnx
djazzc September 26th
Maybe you need to be more precise on the php version, it took me a while to figure out why your code was not working….
JSON encoding and decoding is built into PHP since PHP 5.20 and my server is running 5.1.3
( )djazzc September 26th
But with the function written by andyrusterholz, which you can find here: http://fr.php.net/json_encode in the User Contributed Notes, I got this baby even running on PHP4, great work all you guys.
PS. I am not the worlds greatest programmer but I sure know how to copy paste
( )P@T-From p@ris October 30th
Do you the script in ASP!
( )Thanks a lot