Tutorial
Introduction to AJAX
by Void | in Javascript | posted December 09, 2006
![]()
![]()
![]()
![]()
(1 vote) | 2369 views
What is AJAX, what it is not, how it works. What are AJAX frameworks. The XMLHttpRequest object. Short introduction to AJAX with a basic example.
Add to del.icio.us |
Digg this |
Dot This
HTTP is stateless protocol that works on request-response basis. This means that when a browser is "directed" to an URL, it connects to the server addressed in the URL and sends to it a GET request which includes the path to required filename (or resource), including any queries. Such request may also contain POSTed data in its header. The server then responds to this request returning the required resource or another message/resource (for example, if an error occurred). And here is where the communication between the browser and the remote server ends. Another request is entirely new communication which again assumes connecting, sending of GET request with optional POSTed (or another) data, receiving resource/response from the server. Of course, there are exceptions to this "entirely new", since sessions can be tracked, connections kept persistent, etc... which is completely out of the scope of this tutorial. The point is, every time you click a link on a page, entire page is loaded, even if there are only few bytes changed on an otherwise kilobytes of page data. With some exceptions, each click leads to a "new" page as far as the browser is concerned, and that's why entire resource is reloaded. Smart browsers (almost all of them nowadays) first check if resource changed since last time it was accessed, and load it again only if it changed.
In some situations this browser behaviour is cumbersome and unwanted. Sometimes page design calls for interactivity with the server without having to reload entire page. This is where AJAX (as a programming concept) and the XMLHttpRequest object are used. However, as we will see shortly, AJAX is not used only to respond on clicks to links. Actually it seldom is, in a strict sense of the word "link". Javascript can track all kinds of user actions, mouse movements, mouse clicks, keystrokes, changes of form element focus, drag and drop actions, etc... For all these actions, with Javascript, you can issue a background call to server and fetch some data. This is where the strength of AJAX is.
It's all about XMLHttpRequest
Well, yes and no, but for the purpose of this tutorial let's say that entire AJAX philosophy is mostly revolving around the usage of XMLHttpRequest object in Javascript. So, what is it and how does it work?
First and foremost it is an object (as in OOP object) that has properties, methods and events designed to perform HTTP requests with remote servers in the "background". "In the background" means that the object can issue such requests without having to reload entire page. You can think of it as a small "browser" in itself that can "go to" URLs and store data returned by servers at those URLs. For the purpose of this tutorial it is assumed that you know what Javascript objects are and how they work.
What is important here is to know that XMLHttpRequest object issues same HTTP requests that the browsers do. This means that you can issue calls to PHP or ASP, or whatever server-side script, on the server which will format data according to your request. XMLHttpRequest, as its very name says, does not use some "other" type of communication protocol, it uses good old HTTP. So the server actually does not know that you issued a call with XMLHttpRequest; as far as the server is concerned, your browser issued a regular request. This also means that with such calls cookies and browser information are also included, as if you manually entered the request in the browser address bar.
For more information about XMLHttpRequest, consult the W3C reference page. Note that Microsoft originally introduced this object, so lovers of MSDN can find adequate reference there.
Let's see how XMLHttpRequest works through a simple example. First the code will be presented, with comments, and later description of what we did:
Code:
// Create instance of XMLHttpRequest class and call it 'remote'
var remote=XMLHttpRequest;
// Supply the function that will respond to state changes
remote.onreadystatechange= connectionHandler;
// Open the connection and send the request
remote.open("GET", "http://example.com/somescript.php");
remote.send();
function connectionHandler() {
// If connection established, and server responded ok (200)
if(this.readyState == 4 && this.status == 200) {
// If the server returned some data
// Call our data handling function and pass the data to it
dataHandler(this.responseXML);
} else if (this.readyState == 4 && this.status != 200) {
// If connection established, but server responded with an error
// handle server errors
...
} else ... // handle connection errors
}
function dataHandler(data) {
// Handle data here, in XML format
var field= data.getElementById('somefield').firstChild.data;
//...
}
Now, let's see what happened. For practical reasons, let's assume that the code given above is in response to a button click, so when the user clicks a button, the above code will execute.
First we have created our XMLHttpRequest object and we called it 'remote'. We then supplied function name 'connectionHandler' to its property onreadystatechange. Why? For various reasons the object was designed to call a function when internal state changes. This way the function can handle connection status and data receiving independent (asynchronous) of the rest of the Javascript code. This is very powerful as it allows background communication while your code does something else.
Next, we opened a connection to the remote server using GET protocol, and then we sent the request. Note a few things here: if you want to send a POST request, naturally you would supply "POST" instead of "GET" in function open(). You then supply your POSTed data in the send function, for example remote.send("somevar=somedata");. If you want to send both POST and GET, use POST, and supply GET data through the url:
Code:
remote.open("GET", "http://example.com/somescript.php?anothervar=anotherdata");
remote.send("somevar=somedata");
You format the POST data according to HTTP POST request header rules: var=data;var2=data2;var3=data3...
What now? After we send the request, the object will call the function supplied in onreadystatechange property, when connection state changes. In our example that is the connectionHandler() function. What this function do is arbitrary, and up to our design, but we don't have much choice but to poll readyState and status properties (variables) to see what happened to our request. There are 4 values readyState can contain. See the above given W3C reference for these values. You can respond to any of the states if your code calls for it, but for some basic AJAX, code 4 (Data Loaded) is of interest.
Note that data loaded means only that TCP/IP connection to the server was successful, and server returned (some) data. That's why we poll the status property to see what the server said (response status code). This property contains standard HTTP response codes. Our example expects code 200 which means the request was processed successfully on the server side. With this we can assume that the remote script (or whatever resource we called) returned expected data. This data is held in responseXML property, so we pass the contents of this property (the actual data loaded) to our data handling function. What we do with the data is up to the code logic and application design, however note that the data is in standard Document Object Model (DOM) format, meaning nodes and their attributes and values are available through DOM functions.
Our connectionHandler() function therefore can also handle both connection and server errors. Such handling can be anything from attempted retries to notification of the user about failed request, or something else.
It must also be mentioned that XMLHttpRequest need not only fetch XML data. The object has property called responseText that contains text representation of the received data. This also means that the request will not error-out if the server returns non-XML data. In such case the responseXML will remain void, and responseText will contain whatever the server returned. This is particularly useful for applications that need quick and simple responses, or simple, single-node data for which XML is not necessary, or to return non-textual binary data that would make XML invalid if not escaped (which increases bandwidth).
AJAX Frameworks
In short, AJAX Frameworks are collections of code that make AJAX programming much easier. Such collections are usually classes wrapped around XMLHttpRequest that facilitate formatting of the request and receiving of data, as well as handling errors. For a most basic AJAX application, a Framework is not required, and usually it is best to write your own wrappers according to your application needs and design. There are many such frameworks on the internet.
AJAX Applications
So far we have seen what XMLHttpRequest object is and what it does. With this in mind we can design any application that requires background asynchronous communication with a remote server. Whether your application requires AJAX approach depends on many things. Here are some useful ideas.
You can issue asynchronous calls to validate form data. For instance, during registration of users to your website, you can check if the supplied username (or email, or something else) already exists. You can respond to changes in a drop-down box, and dynamically load parts of the form according to the selected drop-down item. This is particularly useful since it avoids having to load entire web page on each selection.
You can have timed updates to parts of the presented page, without the need to reload entire page. This not only saves bandwidth, but looks nice and seamless. Sometimes you will need to poll different servers, or different resources on the same server, but at different times (for whatever reason) which is possible only with asynchronous data fetching, since page reload is synchronous.
You can respond to what user types in a text input box, and return suggestions according to what the user wrote so far. Example of this is Answers.com which returns suggestions of searched terms as you begin to type first characters of your query.
You can do much more with AJAX approach, but it all depends on what you need. Of course, there are always limits to what you can do. It is worth mentioning that AJAX is not advised as main platform of website navigation since parts of the website are accessed through javascript and therefore they lack uniform resource locators (URL) which someone can bookmark, or jump to directly. At least the critics are mentioning this as one of the major flaws of AJAX - but they don't understand that AJAX is not all-in-one solution and replacement for, say, Flash, but a philosophy and approach to handling data. Even the lack of URLs with AJAX navigation can be easily fixed by providing a button or link that will bookmark the content in your browser, and by providing a server-side script that will return requested content.

