Dynamic AJAX content - JavaScript
Written by Python - Wednesday 28th of May 2008
Links - a thing of the past? Probably not but with the use of JavaScript/AJAX it is possible to offer the user with a slightly different site navigation experience. This tutorial will show you how you can dynamically change the contents of your web pages with the click of a link by using a little bit of AJAX and JavaScript.
Table of contents
1. What we want
AJAX, depsite what a lot of people think is actually quite an old technology. Its recent explosion in popularity has essentially happened because some of the major players including Google, Yahoo and Microsoft started playing with it in their web services. Since then more and more people have been implementing these relatively easy to use techniques in order to create some pretty cool stuff.
One of the primary functions of AJAX is being able to access other files on your server (or anywhere on the web) without the end user really knowing about it. The example demonstrated in this tutorial does exactly that and will allow you to change a pages content on the fly. This when used correctly can create all sorts of really interesting sites but to keep things simple the example used here will just be used to change over a few content boxes.
2. Let's get started
Okay. To begin with I will quickly explain how this will work. We will have our index.html page which is of course our homepage. Attached to this will be our JavaScript script which is the 'brains' of this tutorial. Then we will have two other files - one called page_home.html and the other page_contact.html. Then when we click on a 'Contact us' link this home content will be replaced by the contents of page_contact.html. On top of that I have then used a simple style.css stylesheet which sets some basic styling rules for the document. All of this will be done quietly in the background without the need for a single page reload.
Firstly lets create all of these HTML files and then we will look at the JavaScript.
Here is our index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Dynamic AJAX content tutorial example</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
</head>
<body>
<div id="container">
<h1>Dynamic AJAX content tutorial example</h1>
<a href ="#" onClick="loadContent('page_home.html', 'content');">Home</a> | <a href ="#" onClick="loadContent('page_contact.html', 'content');">Contact us</a>
<div id="content">
<!-- Content will be dynamically loaded into here -->
</div>
</div>
</body>
</html>
Here is our page_home.html
<h2>Homepage</h2>
<p>
This is a demonstration of dyamically loading content using AJAX and JavaScript.<br/>
You will find it here at <a href="http://www.codingtuts.com/coding-tutorials/javascript/page-objects/dynamic-ajax-content">CodingTuts.com</a>.
</p>
And then our page_contact.html
<h2>Contact</h2>
<p>
Interested in contacting us?<br/>
Email us: some_name@website.com
</p>
Here is my style.css - You don't really need this but I have included it just so that you can replicate my page exactly if you so wish.
*
{
margin: 0;
padding: 0;
}
body
{
background: #333;
}
h1
{
font-size: 1.6em;
}
h2
{
font-size: 1em;
}
#container
{
width: 400px;
background: #FFF;
padding: 30px;
}
#content
{
border: 2px solid #CCC;
margin: 10px;
padding: 15px;
}
a
{
color: #333;
font-weight: bold;
}
Now you might have noticed that page_home.html and page_contact.html is much less than index.html. That's because we don't need to include any of the html/head/body related tags as this age will be pulled dynamically into our main page.
3. The JavaScript/AJAX
Now that we have sorted out all of the other files we can now concentrate on the brains behind this script, our javascript file. Here it is in full - I have named it js.js.
var myHttpRequest = false;
if(window.XMLHttpRequest)
myHttpRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
myHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
function loadContent(source, content)
{
if(myHttpRequest)
{
var data = document.getElementById(content);
myHttpRequest.open("GET",source);
myHttpRequest.onreadystatechange = function()
{
if(myHttpRequest.readyState==4)
data.innerHTML = myHttpRequest.responseText;
}
myHttpRequest.send(null);
}
}
Now let me explain what's going on.
To begin with on line 1 we are creating a new variable called myHttpRequest and giving it the value of false. We need this variable for later use throughout the script.
From lines 3 to 6 we are using a simple if/else-if statement to determine which object we should use. Essentially this statement is used to determine whether or not the visitors browser is Internet Explorer or something else. If it is IE then we have to use ActiveXObject() instead of XMLHttpRequest(). Depending on which branch of the if/else-if stateent is true the variable my httpRequest will be set appropiately.
On line 8 and onwards we then create a new function called loadContent(). It has two arguements which are the source and content. The source is the filename of the file which we want to pull into our page. The content is the ID of the element in our page in which the source will be placed.
Within our loadContent() function we have an if statement which checks to see if the variable myHttepRequest is set. If it has not been set then it means the visitors browser does not support thi functionaity and will therefore do nothing. If however the variable has been set then execution will continue.
The next few lines, 12 to 22 are all about loading the pages content (whose filename was provided by the source arguement of the loadContent() function). The if statement on line 18 checks to see if the state of the request is equal to 4. Having the state of 4 essentially means that the files content was returned succesfully. Within that if statement we are then setting the inner HTML of our data item (which was provided by the content arguement of the loadContent() function) to the contents of our loaded file.
Thats the JavaScript over and done with. But how do we get this to work with our links? Take a look at this.
<a href="#" onClick="loadContent('page_home.html', 'content');">Home</a>
By setting the onClick property of our link to point to our loadContent() function this will then execute it as needed. Simple!
4. Loading the first page
If you have followed this tutorial correctly and have been tryng it out for yourself you should be able to see one small problem. When we open index.html in our browser our content div does not actually have any content. This is because as of yet we haven't clicked on any of the links therefore our loadContent() function has not loaded anything in.
There is a very simple fix to this. Simply add an onLoad property to the body tag of your index.html page. This means that as soon as the page is loaded in the browser our loadContent() function will be called which will pull in the relevant page. This is what your opening body tag needs to look like.
<body onLoad="loadContent('page_home.html', 'content');">
And that's it - that's all there is. You can see this in action here. The files used in this tutorial can also be downloaded from here.


Perfect

You must be a registered user to add your comments.
15-10-2008 About my previous post:
Ofcourse I mean:
echo "session var= ". $_SESSION['test'];
and not
echo "session var= ". $_SESSION[''];
So this is not the reason why it goes wrong.
:-)
15-10-2008 First of all: great tutorial, and exactly what I was looking for.
But:
I have a question about the PHP session variables when using this piece of code.
I have an index.php file, with a div "content" in it.
Several links in this index.php file will change the content of the div. The index.php file also has a session_start(). I set a session variable right after session_start(): $_SESSION['test'] = 'X'.
One of the content-file files is a form (it does not really matter what kind of page is). But when this file is loaded into the content div, the session variables are not known! In the loaded page I have:
echo "session var= ". $_SESSION[''];.
But it doesn't show the 'X' as it is supposed to.
How can I make sure that the session variables are still available in the new content, after the content page has been loaded by loadContent?
I hope my question is clear and a solution would be extremely welcome!
Regards,
Cyrus
5-9-2008 Hi everybody,
IE is a bit tricky at that point. IE needs to be served the server document as text/xml, even if it's not regular xml. It can be done using eg. php header() function. Only then AJAX works on IE. I hope it helps.
7-8-2008 This is awesome but, I'm unfortunately having the same problem as mindfullsilence. I'm creating a web site for my company and we need to be able to have it viewed in IE and Firefox. Any suggestions?
4-8-2008 this is an awesome tutorial, exactly what I was looking for because I don't want to have to use SSI for a site I'm designing. A "small" problem though. Not sure if it's only my computer but the content that should be dynamically loaded isn't doing so in IE. Everything works fantastically in Firefox but in IE the 'content' div is blank no matter what. Any ideas? I've fiddled with my security settings for about half an hour but to no avail.