A Simple AJAX Driven Website with jQuery + PHP

Written by Kevin Liew on 08 Jul 2009
398,112 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
ricardo 15 years ago
Great tutorial, im new to ajax and learned alot.

just got one question is it posible to pass an variable to the page loader.php. i'm using an php array with pages that people can open but i cant access that now.
Reply
Avangelist 15 years ago
@Mike - you can set the default page using the switch query in php.

After all your cases you can set a default, can't remember what it is off the top of my head but you should be able to search for it pretty easily.
Reply
kevin Admin 15 years ago
@Ricardo: ohhh... passing an array... unfortunately, you can't do that using GET method. But there is a way around it... explanation:

javascript array structure:
var[0] = 1;
var[0] = 2;
var[0] = 3;

you can implode (javascript join() method) a symbol and output them in one line, like this:

var = 1|2|3

then pass it to the URL something like this:

loader.php?page=page&var=1|2|3

and in the PHP part, use explode to convert them back to array again:

$var = explode('|', $_GET['var']);

:) am straight to the point?
Reply
Ricardo 15 years ago
thx Kevin,
Tried it with an array but doesnt work, i used an loop to echo all the values.
But i was hoping there is a way to pass an array to the loader.php file.
Reply
ricardo 15 years ago
Thx kevin,
i hoped there was another way since i also use alot of functions and classes on my pages, that i cant access this way.

but anyway thx for this great tutorial.
Reply
kevin Admin 15 years ago
Hi Aistis, not sure what do you mean by that, include file should be working. More info?
Reply
Aistis 15 years ago
When I write an include code instead of plain text it shows me my included file and nummer 1 for exmple: "The date is 2009-08-03. Have a nice day!1"
Reply
Aistis 15 years ago
Forgot to mention that I'm using php include in the loader.php file
Reply
Aistis 15 years ago
I use a PHP include command in the loader.php

Check my website for the example (Note: click one of the button on the right side to see your script in effect).
Reply
Aistis 15 years ago
Sorry for double posting again, but I didn't know you are blocking php commands in comments. So I'm trying again, here it is:

switch($_GET['page']) {

case '#page1' : $page = include('i/pm.php'); break;

case '#page2' : $page = include('i/friends.php'); break;

case '#page3' : $page = include('i/menu.php'); break;

case '#page4' : $page = include('i/offers.php'); break;

case '#page5' : $page = include('i/adcheck.php'); break;

case '#page6' : $page = include('i/faq.php'); break;

}
echo $page;

I hope you can see the code this time =)
Reply
kevin Admin 15 years ago
Hi Aistis. I see what's the problem, i dont think u can include a file and assign it to a variable, you need to change your php code to:

switch($_GET['page']) {

case '#page1' : include('i/pm.php'); break;

case '#page2' : include('i/friends.php'); break;

case '#page3' : include('i/menu.php'); break;

case '#page4' : include('i/offers.php'); break;

case '#page5' : include('i/adcheck.php'); break;

case '#page6' : include('i/faq.php'); break;

}


that should work.. :)
Reply
Aistis 15 years ago
Yeap, it works. Thanks =)
Reply
herupermana 15 years ago
Great Powerfull Website, Thanks for Infomation
Reply