A Simple AJAX Driven Website with jQuery + PHP

Written by Kevin Liew on 08 Jul 2009
382,078 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
Anand Kumar Chaudhary 10 years ago
I'm using Wamp server and at the end of every page m getting this error '; break; } echo $page; ?>

and also the content of all the pages are loading at once.....check your download .zip files again.......
Reply
Kevin Liew Admin 10 years ago
You need to make sure your php is installed properly. I checked the download file and work perfectly fine in MAMP for mac. Create a php file, and put in <? phpinfo() ?> see if it displays all the info of your server.
Reply
Niwzat 10 years ago
hi i have some html pages.i wanted to implement ajax code for flash my banner.i copied script but i cant fix loader.php for my html pages.
and this one didnt work for me
//Get the page parameter from the url
switch($_GET['page']) {
case '#page1' : include 'page1.html';
break;
case '#page2' : include 'page2.html';
break;
case '#page3' : include 'page3.html';
break;
case '#page4' : include 'page4.html';
break;
}
Reply
nevzat 10 years ago
hello i have some html pages and i want to import ajax for my banner.i made a index.php and imported to codes in it.i also add include function to import html pages on loader.php.but it doesnt work need some help at this point ty for shearing
Reply
Kevin Liew Admin 10 years ago
do you run local webserver?
Reply
nevzat 10 years ago
Hi i am a beginer to this so i have some problem now.i download the demo and imported to my project.i changed loader.php according to my html pages but when i click navigate links content does not appear.actually the problem is loader.php doesnt work till i downloaded.i use dw cs5.please i really need help or i am getting crazy :p
Reply
Kevin Liew Admin 10 years ago
You need to setup web server environment in order to run loader.php -> apache and php.
http://www.apachefriends.org/en/xampp-windows.html
Reply
nevzat 10 years ago
i do use wamp already and other functions seem work well. i tried include and echo commands and they worked.i dont know what am i doing wrong thx for response. and sorry for couple comments.
Reply
Kevin Liew Admin 10 years ago
Hi nevzat. good that's mean your php is working. I will propose a few ways to debug it hopefully will keep you busy for a while.

Can you try to access to your page by using the loader directly?
http://www.someurl.com/loader.php?page=page1 (you will have to change page1 according to your setup)

Use firebug "Net" tab to see if the jquery script calling loader.php. You should able to see data passed to loader.php and also data returned by it.

Let me know how it goes.
Reply
nevzat 10 years ago
yesterday i downloaded firebug and even i dont know how access my page using the loader i found someway actually i havent changed something but the project which i downloaded worked.
i have started to implement on my website. but i have to confess without knowing php its useless to working on it.
i really appreciated for your help.
Reply
sai 10 years ago
i am applying ajax function in the registration form but in that page jquery validations are not working why?
Reply
Chris 10 years ago
I've faced this when I was creating a mock queuing system, where the status would need to constantly update but also need some scripts to be passed through them after they were loaded with ajax (i.e. toggles).

A work around I found was binding the scripts to the ajax after I called them. For this, I think you can bind whatever callback you want to be done.

I believe this could work:

change
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
to
//add the content retrieved from ajax and put it in the #content div
$('#content').load(html,function(){
$("#button").click(function(){ //Locate the button within the loaded content
//Whatever validation or clickage you want to be done
})
});

This *should* allow for whatever post pages called with ajax to see that it you want addition actions to be taken upon it.....or i could be completly wrong and things may blow up.
Reply
kuldeep 10 years ago
history didnt work in google crome browser????
Reply
Kevin Liew Admin 10 years ago
It works for me. History.js also supports Chrome 4+
Reply
PHP Developer 9 years ago
History buttons are not working on Chrome 17.0.963.56 (like Back and Forward button) any clue how to fix it?
Reply
Ian Venskus 10 years ago
Instead of adding text in the case I was able to add an include. This allowed for a cleaner loading file.

<?

switch($_GET['page']) {
case 'bio' : $page = include ($_SERVER['DOCUMENT_ROOT'].'/bio/index.php'); break;
case 'clients' : $page = include ($_SERVER['DOCUMENT_ROOT'].'/clients/index.php'); break;
case 'portfolio' : $page = include ($_SERVER['DOCUMENT_ROOT'].'/portfolio/index.php'); break;
case 'contact' : $page = include ($_SERVER['DOCUMENT_ROOT'].'/contact/index.php'); break;
}

?>

From there I wanted to allow for Deep Linking and this script will do the trick:

<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
} else {
header("Location: ../#/portfolio");
}
?>

Where it says header (Location etc. just put where you want the page to redirect to. This should be the first thing on the page. In this example the first thing on the Portfolio page.

This way you can send out a link without a hash. So for example http://44lizards.com/portfolio deep links to http://44lizards.com/portfolio

Thank you,
Ian

Reply
Kevin Liew Admin 10 years ago
Hi Ian, thanks for your comment. Yes, that's exactly how it should work, by using include.
Reply
Leticia 10 years ago
That second part should be put where? The rest of the code remains the same?
Reply
joe 9 years ago
Would it be possible to include the code for the php includes. im having trouble making it work!?

Thanks in advance
Reply
Kevin Liew Admin 9 years ago
Johnny 10 years ago
Hi, first of all - great example.And one question: when someone enter site (www.example.com), it is empty, unitl he click on some link (www.example.com/#page1).How can i add some text to there?
Reply
Kevin Liew Admin 10 years ago
You can use this function: pageload(hash) to load page on document ready.
Reply
Varemenos 10 years ago
I tried placing placeload(hash); in my document ready function but it said hash was not declared.
I then tried placing a string for example placeload("#home") or the full url place("/#home"); but nothing worked.

Any help? (im using include to load my pages)
Reply
Varemenos 10 years ago
For now what i did is:
if(window.location.pathname=="/") window.location.replace("/#home");

but im not sure if its a good permanent option
Reply
Esteban 10 years ago
How could you deal with pagination. Eg: A website with menus, and at the same time multiple pages containing news posts
Reply
Kevin Liew Admin 10 years ago
Sorry, it won't be covered in this tutorial as it's a completely new and rather complicated topic. The most basic implementation is to pass two parametesr - start (which row to start) and total (how many records at a time).. so you send this request to PHP script, and PHP uses MYSQL command with "LIMIT start, total" to get the next record. After that, output it and pass it back to javascript to output it. You will need to create hidden fields to maintain the start and total value.
Reply
vinit pratap singh 10 years ago
Thanks for this tutotial, only one thing if i want to change document title on every click how can i did
Reply
Kevin Liew Admin 10 years ago
Yes you can, you need to add the title to each of the link in the menu:

<li><a href="#page4" rel="ajax" title="Contact Title Put Here">Contact</a></li>

Then, inside this: $('a[rel=ajax]').click(function () {

add this line:

$('title').html($(this).attr('title'));

Should work.
Reply
Gunjan Singh 10 years ago
is it possible load new page with jQuery scrollbar in that page... i tried but its not working..
Reply
Kevin Liew Admin 10 years ago
I guess you need to re-initialise the jquery plugin everytime the content is refresh.
Reply
Greg 10 years ago
Hey I have a problem with loading index page without blank and getting content on links only. I partialy solved it with making case1=page1 blank and starting with real content on page2 inside the loader.php. Problem is that transitions dont' look too good (slideDown which i used instead of fadeIn) since element 's css properties are not preset in parent div id which is content, but in subdiv inside each case in loader.php..

I would like to ask you for a solution for a blank first page, preferrably inside the javascript part..

best regards
Reply
Kevin Liew Admin 10 years ago
For blank first page, I think you can just hardcode it in the HTML.
Reply
error 10 years ago
Hi, Is there a good way to pass javascript through AJAX that you know of. I am working on a site now, and I keep getting loading errors.

This is an example from my loader page.

switch($_GET['page']) {

/*------------------------ ------------------------ ------------------------ ------------------------ */

case '#YELLOW' :

$page = '

<div id="slider">
<ul>
<li><a href=""><img src="http://localhost/easy/archive/YELLOW/images/1.jpg" alt="" /></a></li>
<li><a href=""><img src="http://localhost/easy/archive/YELLOW/images/2.jpg" alt="" /></a></li>
<li><a href=""><img src="http://localhost/easy/archive/YELLOW/images/3.jpg" alt="" /></a></li>

</ul>
</div>

<script type="text/javascript">
$(document).ready(function(){
$("#slider").easySlider();
});
</script>

';

break;

I am pretty sure that the problem is with passing the javascript through the ajax, although at times it seems like a css error.

I also read somewhere that I should use the eval(); function, but I am not sure really how that would work.

Thanks for the help in Advance.





Reply
Kevin Liew Admin 10 years ago
Try remove the document.ready, so just:

<script type="text/javascript">
$("#slider").easySlider();
</script>
Reply