🔍
Hide
A Simple AJAX Driven Website with jQuery + PHP

A Simple AJAX Driven Website with jQuery + PHP

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!


AdvertisementYou can easily check out our best quality 646-046 prepare you well for the real ccda certification. You can also get success in real exam of 650-987 dumps with the quality 640-864 questions and 642-185 answers.

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

178 Comments

Balázs, Hungary
Wed, 18th July 2012
This is indeed a very useful tutorial, thank you so much! However, I cant figure out, wether it can be implemented in multi-level environments too (several ajax-sub-calls with ability to browse back/forward). Is this possible? Reply
Paulo
Fri, 7th September 2012
I've created a library that create a seamless connection between jQuery and PHP, through AJAX json responses. It's highly flexible, and can fit any type of app or website. http://phery-php-ajax.net/ you may follow the github account too http://phery-php-ajax.net/ Reply
Diego
Mon, 10th September 2012
to avoid the "1" problem at the end of each page change the line in loader.php:

echo $page;
to
return $page;

it worked for me! Reply
ill13
Tue, 6th November 2012
I spent a good 20 minutes trying to get this to work on my local WAMP server. It works great on my remote/paid servers, just not locally. Until I changed WAMP's PHP settings to allow "short open tag" [this just means "allow the server to parse '<?' as PHP code, versus the long form of'<?PHP'"] and then restart WAMP. Great tutorial Reply
Implico
Tue, 20th November 2012
Have you seen this plugin? It allows to transform a standard, traditional website into AJAX-based one, maintaining browser back/forward buttons functionality and visibility for search engines.

Link:
http://www.implico.pl/lang-en/ajaxgetcontent_dynamic_ajax_website,7.html

Sample integrations (in Polish):
http://www.implico.pl/lang-en/ajaxgetcontent_dynamic_ajax_website,7.html
http://www.implico.pl/lang-en/ajaxgetcontent_dynamic_ajax_website,7.html
http://www.implico.pl/lang-en/ajaxgetcontent_dynamic_ajax_website,7.html Reply
Neetu
Thu, 13th December 2012
thanx...... Reply
Kris
Fri, 8th March 2013
Hello, Thanks very much for the tutorial it's very usefull.
I hav one little question. When page is loaded for the first time the content is empty.
How i can assigne the content of page1 to be loaded as a home page? Reply
Kevin Liew Admin
Fri, 8th March 2013
use getPage().

Inside document ready, put:
getPage('pagename'); Reply
Crispijn van Sas
Wed, 13th March 2013
Hi Kevin,
This script is pretty useful. I will use it for a website where an image slider be fed with new texts and series of images that in the future will be uploaded via simple forms. Do you think it will be wise to store all image paths on mysql or is there an easier way loading multiple images with specific names and incremented numbers via php? Reply
Kevin Liew Admin
Sun, 24th March 2013
It really depends. How often do you update this website? Is it database driven? If it's database driven, it's best to save it in database. Reply
pankaj thakur
Wed, 20th March 2013
Hello, Thanks very much for the tutorial it's very useful.
I hav one little question. i have four services pages, one and down second then down third .
and i have three different pages for each services pages which store in database. when i implement this code i am enable to use on first services page. but when i implement it for 2nd so on... then it will not work? Reply
Kevin Liew Admin
Sun, 24th March 2013
Does it display any javascript error? Use firebug or developer tools to debug. Reply
m4rus
Thu, 18th April 2013
Thank you so much! Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement
Advertisement