Making an Ajax Website

This tutorial will tell you how to apply ajax to make a website completely in ajax. It isn't required to know how to use ajax for this tutorial and you could probably apply it without knowing javascipt either. The focus is on the application of ajax to make a website with it.

The reason for using ajax is to make your website load more quickly and smoothly and reduce load on your web server. It is also useful if you do not have access to a server side scripting language because you can seperate the parts of the page that are persistant over all of you pages such as the links bar and title from the content that varies. This makes a website a lto easier to maintain obviously because if you add a link for example it only needs to be done in one place and it is applied over all of the site.

This is similar to the way in which you could use frames. Frames have long been considered poor practice though, since they cause problems with some browsers and linking to and bookmarking pages. The only thing in this tutorial that isn't just the normal ajax is in fact the method for allowing external links and bookmarks to function correctly.

HTML Structure

The html for this example will be very basic. It will consist of a links bar and a main content box. You can just add anything else that you wish such as a logo as long as you keep it outside of the content box.

<html>
<head>

<title>My ajax website</title>
<script language="Javascript" type="text/javascript" src="ajax.js"></script>

</head>

<body>

<div id="nav">
<a href="#index">Home</a> | 
<a href="#about">About Page</a> | 
<a href="#rand">A Random Page</a>
</div>
<br/>

<div id="content">
</div>

</body>
</html>
You will notice that the links are slightly different from normal. You will probably know that this means they are internal links, linking to a section of the current page. We will not be using them properly, they are there because they change the url of the web page. This means that people can then bookmark it or link from another website since our javascript will read the url.

There is a link to an external script called 'ajax.js'. This will contain the ajax code. It is good practice to seperate the code to keep your pages tidy.

The only other thing to note is that there is an empty div with an id of 'content'. This unsurprisingly is where the content of the pages that ajax fetches will go.

The Ajax Code

I have used the code from another tutorial that I found. Unfortunately I cannot find this tutorial so I can't give due credit. If anybody knows please tell me. Most of it is standard ajax which I won't bother explaining, I have in fact only changed one line.

This code should go into ajax.js which we have already included into our main html document.
function createRequestObject() {
	var req;

	if(window.XMLHttpRequest){
		// Firefox, Safari, Opera...
		req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		// Internet Explorer 5+
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		// There is an error creating the object,
		// just as an old browser is being used.
		alert('Problem creating the XMLHttpRequest object');
	}
	return req;

}

// Make the XMLHttpRequest object
var http = createRequestObject();

function sendRequest(webpage) {
	// Open PHP script for requests
	http.open('get', webpage);
	http.onreadystatechange = handleResponse;
	
	http.send(null);
}

function handleResponse() {
	if(http.readyState == 4 && http.status == 200){

		// Text returned FROM the PHP script
		var response = http.responseText;

		if(response) {
			// UPDATE ajaxTest content
			//alert(response);
			document.getElementById("content").innerHTML = response;
		}
	}
}
document.getElementById("content").innerHTML = response; is the bit that I have done. All it does is take the response from the ajax script (the contents of the page that has been asked for) and puts it into the 'content' div.

Making the links work

Now that we have the script set up we can sort out our links. These currently look like:
<a href="#index">Home</a>
Now we need to add an onClick event so that we can run some javascript when the link is clicked. The javascript will call the sendRequest() function. This function only takes one parameter which is the name of the webpage. So it will be onClick="sendRequest('page.html')". Here you should remember that you can't use index.html for your index page content since this file is taken up with your main script. I called mine home.html. This makes the links:<
<a href="#index" onClick="sendRequest('home.html');">Home</a> | 
<a href="#about" onClick="sendRequest('about.html');">About Page</a> | 
<a href="#rand" onClick="sendRequest('rand.html');">A Random Page</a>
You should now create these pages. They should not be full html pages, they are just what code need to go into the content div so they will be mainly text. Mine are in fact just one line of text.

Now your page should work so I would test it. Note that no text will show when you first open the page since we haven't called the sendRequest function until a link has been clicked. Also this will not work unless you have the script on a web server. This is because of the way the javascript sends the http request. It is easy to install a server such as xampp for testing if you don't have anything already.

Page Initialisation

Now everything works other than when the website is first loaded the content is blank. This is clearly no good so now I will show you how to get content loaded properly.

This javascript code must go inside the content div. This is because when browsers load a page they run the javascript code in the head before the DOM is properly constructed. This is obviously no good because it will nt be able to find where to put our content so we put the javascript into the div just to make sure it has loaded far enough. Here is the code:
<script language="Javascript" type="text/javascript">
if ((window.location.href.split("#", 2)[1] == null) || (window.location.href.split("#", 2)[1] == "") || (window.location.href.split("#", 2)[1] == "index")){
sendRequest("home.html");
}else{
sendRequest(window.location.href.split("#", 2)[1] + ".html");
}
</script>
The code first checks to see if the user wants the index page. This could be asked for in three ways with urls of "example.com" which gives null "example.com#" which give "" or "example.code#index" which gives "index". The if statements checks for all of these. If one of them is true then it sends a request for home.html.

If the request is not for the index page then a request is sent for a page based on the url given. The url is plit on the # and then the .html is concatenated onto the end to give a valid page.

Conclusion

An ajax website is clearly fairly easy to make. There are some disadvantages to the method, The largest one is that the user cannot go back to a previous page in your site. I believe that this might be possible to implement in firefox since you can go back and it changes the url from #about to #index. I haven't tested how you could detect this however. I do not believe that it is possible in IE though since the entire site is stored as one entry so going back goes to the previous website. I do not think that it is possible to detect whether the back button has been clicked or not.

The other main disadvantage is that javascript must be enabled to view the website, though this shouldn't be much of an issue currently.

© Jonathan Waller 2005; QuantumState Visual Basic