Ajax "Hello World" Example
Written by Nick Dunn published 27th Mar 2006 | 3 replies in the forums
An introduction to what Ajax is and a basic "Hello World" example. Includes a downloadable example and suggests areas for further examples.
What is Ajax?
There's a growing momentum behind newly-launched websites at the moment. Part of the rise of the Web 2.0 concept has been the mainstream adoption of AJAX (Asynchronous JavaScript And XML). Ajax isn't anything new, nor are the technologies behind the name, but they've found a new lease of life on trendy new sites. So what is Ajax exactly? Put very simply, it's a combination of XHTML, CSS and most importantly JavaScript and XMLHttpRequest that allows you to update your web page content without refreshing the page.
Of course, this is an over-simplified example and the funtionality of the Ajax technologies has a far wider scope. But this article will show you the bare structure of an Ajax-type request, and will show you how to use it on your own site.
The Code
The XMLHttpRequest object effectively allows you to GET or POST to a remote script using JavaScript. In our example we will use this object to open a text file and read back its contents. The code that follows creates an XMLHttpRequest object ready for us to use. We check for Internet Explorer since IE uses its own XMLHttpRequest object that is different from other browsers. When the page loads, the createRequestObject function is called and an instance of the XMLHttpRequest object is stored in the variable "http".
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}function getNewContent(){
http.open('get','newcontent.txt');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}function updateNewContent(){
if(http.readyState == 4){
document.getElementById('mySentence').innerHTML = http.responseText;
}
}
</script>
The second function should be called from a page element, such as a hyperlink or a button. This element will trigger the Ajax event (getNewContent), which reads the content text file. The third and final function (updateNewContent) checks the result of the XMLHttpRequest and updates the page accordingly.
A Hello World example
The JavaScript above should be placed within your HTML page, or included as an external .js file. You should create a text file named "newcontent.txt" containing the words "Hello World" and save it in the same folder as your HTML page. Your event trigger element should call the second function, like this:
<p id="mySentence">
<a href="#" onclick="javascript:getNewContent();">Click here to update the page</a>.
When you click the link, this content will be replaced.</p>
When the link is clicked, the getNewContent function is triggered. It calls a text file named "newcontent.txt". The function updateNewContent monitors the progress of the request, and when it is complete, the HTML element with an id of "mySentence" is updated with the text file contents.
Download all files as a Zip file
To make things a bit easier, you can also download the live example and all code referenced in this article as a Zip file.
Further applications
This is the simplest Ajax example I could think of. If you want to make the "Hello World" content dynamic, you can use the code to request an ASP or PHP page rather than a text file. With some simple modification you could pass some parameters to this request and start to interface with a database. In its most complex form, Ajax has been used to build entire interfaces. Gmail and Google Maps for example, use Ajax heavily to create navigation and page content without refreshing the entire browser page. On your own sites it is likely that you will find Ajax useful for the following common features:
- Validating form fields
- Auto-complete form fields
- Updating content based on timers (e.g. an auction)
- Performing real-time spell checking of form fields
- Dynamically loading list/select boxes based on other form choices
Benefits of using Ajax
- Just a small section of a page can be updated without having to reload the entire page. This saves on bandwidth and loading times, and reduces server load.
- The code is lightweight and not very complex.
- JavaScript and the XMLHttpRequest object are supported in all modern browsers
- It's got the geeky cool factor ;-)
Potential disadvantages of using Ajax
- Not everybody has JavaScript enabled in their browser (by choice, or otherwise). You should make sure that your site functionality does not require Ajax and that the site is usable without the Ajax fanciness
- Breaks the back button. Try the example above and click the back button. The original content isn't replaced, as a normal page in your History is. Therefore you should make plans for a function to also reverse any content replacement if necessary
- If content is embedded within JavaScript code then this can reduce the effective accessibility of your site.