A Simple AJAX Driven Website with jQuery + PHP

Written by Kevin Liew on 08 Jul 2009
402,758 Views • Tutorials

Introduction

AJAX is abbrieviated from Asynchrounous javascript and XML. It's not a new technology, but the implementation of a group of technologies to achieve a seamless interaction between client and server.

Typically, xhtml and css to present the information, javascript is used to handle user interactions, and a server side language to perform the users' requests (and normally return data in XML format, in this tutorial, we won't do that), and it all is happening in the background using the Javascript XMLHttpRequest. Javascript plays a main role tie all these technologies together and create the asynchronous interaction between client ans server.

AHAH (Asynchrounous HTML and HTTP) is a subset of AJAX which is another technique, Inspite of retreiving XML, AHAH is retreiving HTML content. Both of them are basically the same, the only difference is the content it returns. Generally, most people will simply call it AJAX, but technically, we should call it AHAH. In this tutorial, AHAH is used.

The Good, Bad and Solutions

The Goodies:

  • Reduce connections and bandwidth to the server, images, scripts, stylesheets only need to be downloaded once
  • Reduce loading timew. User doesnt have to load pages again and again, it all happens in a same page!
  • Increase responsiveness and end user experiences.

The Badies:

  • Browser Back button. AJAX web pages cannot connect with browser history engine. If you clicked on back button, you can't navigate those AJAX content.
  • Bookmark will not work on AJAX webpages. Due to the dynamic content, you might bookmark the homepage instead of the desired page.
  • Javascript is needed. To run AJAX based website, your browser need to have javascript enabled.

The Solutions:

AJAX is not a perfect technology, but some of the limitations can be overcame with some simple solutions. I found this very userful plugin called jquery.history.js. It solves Browser Back Button. For the bookmark problem, we can solve it by appending a hash value in the end of the url.

For the last one - javascript, we are going to ignore it. It can be done but I want to keep this tutorial simple.

And, of course, you'll need a good web server as well, if you're hunting for a web hosting company, you can click here to read reviews about the best web hosting out there! iPage Review

Requirements

You will need the following items and environment to run this script

1. HTML

I will provide two versions of HTML code. The first one is the most basic elements you will need to get it working. And the last one is the one I created with some design

Simplified versions
<ul>
	<li><a href="#page1" rel="ajax">Home</a></li> 
	<li><a href="#page2" rel="ajax">Portfolio</a></li> 
	<li><a href="#page3" rel="ajax">About</a></li>
	<li><a href="#page4" rel="ajax">Contact</a></li>
</ul>

<div class="loading"></div>

<div id="content">
<!-- Ajax Content -->
</div>
		

2. CSS

This is really really simple, just have to keep the loading and content hidden

#loading {
	background: url(images/load.gif) no-repeat;
	display:none;
}
			
#content {
	font-family:arial;
	font-size:11px;
	display:none;
}	

3. Javascript

I have added comments in every single lines of the code.

	
$(document).ready(function () {
	
	//Check if url hash value exists (for bookmark)
	$.history.init(pageload);	
	    
	//highlight the selected link
	$('a[href=' + document.location.hash + ']').addClass('selected');
	
	//Seearch for link with REL set to ajax
	$('a[rel=ajax]').click(function () {
		
		//grab the full url
		var hash = this.href;
		
		//remove the # value
		hash = hash.replace(/^.*#/, '');
		
		//for back button
	 	$.history.load(hash);	
	 	
	 	//clear the selected class and add the class class to the selected link
	 	$('a[rel=ajax]').removeClass('selected');
	 	$(this).addClass('selected');
	 	
	 	//hide the content and show the progress bar
	 	$('#content').hide();
	 	$('#loading').show();
	 	
	 	//run the ajax
		getPage();
	
		//cancel the anchor tag behaviour
		return false;
	});	
});
	

function pageload(hash) {
	//if hash value exists, run the ajax
	if (hash) getPage();    
}
		
function getPage() {
	
	//generate the parameter for the php script
	var data = 'page=' + document.location.hash.replace(/^.*#/, '');
	$.ajax({
		url: "loader.php",	
		type: "GET",		
		data: data,		
		cache: false,
		success: function (html) {	
		
			//hide the progress bar
			$('#loading').hide();	
			
			//add the content retrieved from ajax and put it in the #content div
			$('#content').html(html);
			
			//display the body with fadeIn transition
			$('#content').fadeIn('slow');		
		}		
	});
}

4. PHP

We will not go further on PHP code, this time, I'm using a basic switch to grab the content. The content for the page is being assigned to a variable called "page". And the last line, output the content.

To debug the php script, you can access it by passing data into it, for example:

http://www.someurl.com/loader.php?page=page1

It should display the content for page1. If you know about php and database, you can store the content in the database and retrieve it. Make a simple form to edit the content and BANG... you got yourself a customized content management system.

	

//Get the page parameter from the url
switch($_GET['page'])  {
	case 'page1' : $page = 'Page 1'; 
					break;
	case 'page2' : $page = 'Page 2'; 
					break;
	case 'page3' : $page = 'Page 3'; 
					break;
	case 'page4' : $page = 'Page 4'; 
					break;
}
echo $page;

Conclusion

That's it. Make sure you check out the demo and download the source code and play with it. If you have created your own, feel free to drop your link in the comment section to show off! : )

Last but not least, I need your support :) If you like this article, please help me to promote it by adding this post to your bookmark. Or you can subscribe to my RSS for more jQuery tutorial and design inspiration posts! Thanks!

Demo 1Demo 2Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

188 comments
MCTS EXAM 14 years ago
It's a very good tutorial to atleast start the AJAX implementation on website. I would definately try to have AJAX on my site as the user interaction becomes superb.
Reply
Marlowe 14 years ago
Hey thank you it works but when i want to include a page with the galleria photo gallery but it only loads the html ?
can you help me ?
Reply
Josip 14 years ago
Tips for making IE working with jQuery:


1. Download and use new jQuery skript:
http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js


2. Change this code lines in jQuery script:
---------------------------------------------------------
$(document).ready(function () {

to

$(window).ready(function () {
---------------------------------------------------------
$('a[href=' + document.location.hash + ']').addClass('selected');

to

$('a[href=' + window.location.hash + ']').addClass('selected');
---------------------------------------------------------
var data = 'page=' + document.location.hash.replace(/^.*#/, '');

to

var data = 'page=' + encodeURIComponent(window.location.hash);
---------------------------------------------------------


That's it!

Ajax loads now perfectly in IE and without this changes I get only that the URL is changing but the ajax pages doesn't won't to load...


:: cheers ::
Reply
Phillip 14 years ago
Hi, nice tutorial!

I've used your technique on a website i am developping! It works fine on IE and FF but when i use safari or chrome i'm having some issues. Sometime i'll click on another page and the page will simply reload without changing to the clicked page:

http://deuxhuithuit.com/dev/melanieguay/

If anyone as experienced this problem or has a clue it woulf be greatly appreciated.

Thanks
Reply
ajmal 14 years ago
$('.clickme').live('click', function() {
// Live handler called.
alert("ajax content");
});
Reply
Karen 14 years ago
Demo works fine in IE, but when tried the downloaded code all the links had the same output of all four pages combined written below any of the four buttons when clicked?? For example,

"using the same concept.
'; break; case '#page2' : $page = 'Portfolio
You can put"

Any answers to this one? Thanks
Reply
Karen 14 years ago
Have resolved. For the file loader.php start with a <?php and not just a <? which would result in all the information of buttons on one output the same for all clicks. This corrects.
Reply
Kevin Liew Admin 14 years ago
Hi Karen, you must have the php short hand turned off. But great that you found it out. I once was having that problem and I almost bang my head to wall :p
Reply
Thiaghu 14 years ago
Hey ! I am having problems with step 7! I cant draw the box and then fill it with the gradient? Can you please tell me how you did that? the -90 something? thanks a lot
Reply
Jonathon 14 years ago
Hi all,

Firstly, thank you to the author for writing this. It has given me a good start into the world of AJAX. I did note some of the issues others were having, and so made some adjustments. Notably, I changed:

1. The history init and load calls have been tweaked. These now init and save correctly.
2. I removed the pageLoad function, as it was not needed after the history lib change
3. I have set it to load my home link in the menu on page load. Easy done.
4. Other minor tweaks, like using this rather than statically referencing an object on the DOM

Anyway, my next post has the code. I am happy to be contacted by email abbakiri at me dot com if you would like more info.

Cheers,

Joe


Reply
Kevin Liew Admin 14 years ago
Hi Joe, thanks for your sharing.
Reply
Jonathon 14 years ago
No problems, just wanted to provide some thoughts. The script provided originally was great, but this solved some of the problems experienced by other users.

To anyone reading it, the posts are listed in reverse order, so check you have it the right way around before trying it!

Happy coding!
Reply
Jonathon 14 years ago


$(document).ready(function () {

$.history.init(function (hash){

//Check if url history value exists
if(hash == ''){

//Loads my home data on first load
getPage('home');

//set the home link class to selected
$('a[href=#home]').addClass('selected');

//Search for link with REL set to ajax
$('a[rel=ajax]').click(function () {

//fade out the content and bring up loader
$('#content').fadeOut('slow');
$('#loader').fadeIn('slow');

//grab the full url
var hash = this.href;

//remove the # value
hash = hash.replace(/^.*#/, '');

//for back button
$.history.load(hash);

//clear the selected class and add the class class to the selected link
$('li a').removeClass('selected');

//Used this as it works nicely in JQ
$(this).addClass('selected');

//run the ajax
getPage(hash);

//cancel the anchor tag behaviour
return false;
});

Reply
Jonathon 14 years ago
}else{

//set the hash for the getPage call
var hash = location.hash.replace(/^.*#/, '');

//I remove ALL selected classes
//This has to change if you have other links with selected classes
$('li a').removeClass('selected');

//Fading out the content and in the loader
$('#content').fadeOut('fast');
$('#loader').fadeIn('fast');

//getPage from history
getPage(hash);

//highlight the selected link
$('a[href=' + location.hash + ']').addClass('selected');

}

});

});
Reply
Jonathon 14 years ago


function getPage(hash) {

//generate the parameter for the php script
var data = 'page=' + hash; //'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "core/pageLoader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {

//hide the progress bar
$('#loader').fadeOut('slow');

//for some reason, the ajax call used to bring up the hidden div
//then hide it, then fade it in. Looked bad!
//So, I hide it again here, then we load the data in, then we
//fade it back up. Seems to work nicely now.
$('#content').hide();

//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);

//display the body with fadeIn transition
$('#content').fadeIn('slow');

}
});
}
Reply
shahrooz 14 years ago
it's really good!
i'm iranian.....
Reply