Blog
How to build dynamic websites with AJAX?
4 juli 2010
In this blog post, we will discuss AJAX, and how you can easily implement it to make your website dynamic. And just to be sure: when we're talking about AJAX, we don't mean the dutch football team from Amsterdam. We are talking about the AJAX as an abbrevation for Asynchronous Javascript And XML.
Let's break down the definition:
- Asynchronous: Before AJAX existed, browsers were only capable of displaying new content (fetched from the server) after a full page refresh. That meant that whenever you wanted to update a tiny portion of your website (e.g. refresh a list with recent comments) you had to reload the entire website. Ajax is Asynchronous and allows you to fetch new data from the server without the need for a page refresh.
- Javascript: AJAX uses Javascript to allow these partial page reloads. All browsers after Internet Explorer 6 have implemented the Javascript functionality to fetch Asynchronous data from the server. They implement it in different ways, and that's why it can be very usefull to use a Javascrip-library to help you generalize your code. Our preferred Javascript-library is MooTools, but you can also use JQuery, ProtoType or any other library that you like. Note: the scripts in this article are based on MooTools
- XML - XML is an abbrevation for eXtendend Markup Language and is an HTML-like markup language, that can be used to exchange data between different software. AJAX can return it's results in XML-markup (or HTML), but also in plain text of JSON.
What can we do with it?
Ok. So now we know what AJAX is, it's time to see what we can do with it. In this blog post we will give you the example of how you can easily convert your existing website to a dynamic AJAX-website, by opening the links directly in a content-div, without refreshing the page.
First let's start with a simple example that will open the contents of a link in a <div> on your page:
<html>
<head>
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<a href="test1.php" id="my_link">Test 1</a>
<div id="content">
</div>
</body>
</html>
Ok. Now what we want to happen is that when a visitor clicks the link, our AJAX function get's called, instead of the default action (which would be opening the page "test1.php" in the entire browser window). First we have to intercept the visitors click, disable the click itself and then run our AJAX script.
window.addEvent('domready', function() {
// get the elements with the $-function
var link = $('my_link');
var target = $('content');
// define the AJAX request
var request = new Request.HTML({
url: 'test1.php',
onComplete: function(tree, elements, html, jscript) {
target.set('html', html);
}
});
// add a onclick event to the link
link.addEvent('click', function(event) {
event.stop() // stop de default behaviour
request.send(); // make the ajax request
});
});
Let's explain the code above a little bit.
- First we add a domready-event to the current window. This makes sure that the entire html of the page is loaded before we execute the function. This way we don't get errors about elements not being rendered yet.
- Next we use the MooTools $-function to retrieve the 2 elements on the page: the hyperlink and the content-div. We store the reference to these elements in two variables (link and target)
- Then we create a new Request-object (the Mootools object that will handle our AJAX request) and we configure it to use the url test1.php and to set the result html into the target div (#content)
- Finally we add an onclick event to our link. First we stop de default behaviour of the hyperlink with event.stop(). Then after we execute our request by making a send()-request.
Now, go ahead and try the code above. Don't forget to include the Mootools library and make sure that the file test1.php exists. Upload the files to your webserver and see the magic happen :)
Using it in the real world
In the previous example we hardcoded in the Javascript which link-element to use, which url to follow and where to display our result html. In the real world, this is just not going to work. Imagine you want to convert your entire website to load it's pages asynchronous! We need to generalize our script to work for all the links in our page. Luckily this is not difficult using MooTools. Consider the following HTML
<html>
<head>
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<a href="test1.php">Test 1</a>
<a href="test2.php">Test 2</a>
<a href="test3.php">Test 3</a>
<a href="test4.php">Test 4</a>
<div id="content">
</div>
</body>
</html>
As you can see we now have four different links, and we want all of them to open Asynchronously in de content-div. Now we modify our Javascript to first lookup every hyperlink in our webpage, and then add the onclick event for each of those links.
window.addEvent('domready', function() {
// get the target element with the $-function
var target = $('content');
// get *all* the hyperlinks, using the $$-function
// and traverse each element
$$('a').each(function(link) {
// define the AJAX request
var request = new Request.HTML({
url: link.get('href'),
onComplete: function(tree, elements, html, jscript) {
target.set('html', html);
}
});
// add a onclick event to the link
link.addEvent('click', function(event) {
event.stop() // stop de default behaviour
request.send(); // make the ajax request
});
});
});
Note that in our first example, we hardcoded test1.php. Now we use link.get('href'), to get the actual href of the current link, to make this Javascript work with any link!
Improvements?
Off course this is just a basic example of how to use AJAX to make your links load dynamically. Some suggestions to improve this example to fit your needs:
- Select which links to make dynamic - There are situations, where you don't want every link to be an AJAX-link. We can easily achieve this, by adding a class (e.g. 'ajax') to those links you want to be converted to AJAX. And then use:
$$('a.ajax').each(function(link) - Different target divs - You can also imagine you don't want to use the same target div for each link in your website. Again we can easily add this functionality, by adding a rel="target.." attribute to our links. Then we modify the javascript to use the value in the rel-attribute to act as the target-div.
var target = $(link.get('rel'));
target.set('html', html); - Effects - MooTools and many other javascript libraries come with a range of visual effects. You can enhance your website by adding an effect to each page load. Think of a fade-in/fade-out effect for example.
Conclusion
In this short introduction to AJAX, we've shown that it's quite easy to use AJAX to make a website dynamic. We've used the most basic form of AJAX, simply returning HTML. AJAX has more cool features, but they are beyond the scope of this article, for now.
Our suggestion is to start playing around with AJAX. That's the best way to discover it! We also strongly advise you to use a Javascript framework, as it makes your life a lot easier!
Happy coding!




