articles » current » javascript » ajax-tutorial

JavaScript: AJAX Tutorial

A quick guide to Asynchronous JavaScript And XML (AJAX).

AJAX is a new approach to web interaction. It breaks up an Internet site page into several smaller pieces downloading only what's needed when the user needs it instead of everything all at once. This new technology has made websites more like applications and JavaScript is what has made this possible. The webserver, now, instead of serving just whole HTML pages may be serving up small chunks of HTML, JSON or plain text to support the AJAX requests from the client. AJAX is an acronym for asynchronous JavaScript and XML, but XML rarely plays a role (JSON is popular, however).

One popular example of AJAX is Google Suggest, pictured below.

Google Suggest

As the user types, the browser sends requests to the Google server to return matching search phrases. Obviously, all these data have not already been downloaded to the browser. The data are being retrieved as the user types. The amount of potential search phrases is infinite.

The main object in JavaScript that makes this possible is XMLHttpRequest(). In older versions of Internet Explorer, it has a different name, but it functions the same.

When AJAX Is A Good Thing

AJAX is useful when updating part of a page, preventing a full postback to the server. This looks faster to the user and reduces server load.

When AJAX Is Not A Good Thing

When the user disables scripting in their browser to make it more secure, AJAX applications no longer function. Also, when the user uses the back button on an AJAX enabled site, there is no history of changes on the page so the back button will usually take the user farther back than they expect. Finally, having too many connections open to the server can degrade performance. For example, using AJAX to update the whole page could open dozens of connections all at once. The work-around is to load the whole page during the single connection when the page is first requested — be it in JSON or HTML snippets or not — and then update page sections as needed. Some sites just send the first part of the page and then the later parts as the user scrolls down.

Now let us look at some code.

var obj = new XMLHttpRequest();
obj.onreadystatechange = function(){
	if(obj.readyState == 4){
	if(obj.status == 200){
		document.getElementById("div1").innerHTML = obj.responseText;
		throw new Error("XMLHttp status " + obj.status + ": " + obj.statusText);
};"get", "ajaxpage.html", true);

The var obj = new XMLHttpRequest(); statement is creating the object. Then, obj.onreadystatechange = function() assigns a function to the onreadystatechange event which fires whenever there is a change in the ready state. The readyState we are insterested in is 4, if(obj.readyState == 4), which is the final ready state once the server and client are done communicating with one another. if(obj.status == 200) checks that the server was successful and returned what we requested. A value of 500, for example, means there was a server error and the data will not be what was wanted."get", "ajaxpage.htm", true); issues an HTTP GET request to retrieve ajaxpage.htm and the true parameter means that JavaScript execution should continue and that communication should be done asynchronously; the onreadystatechange function will be called. obj.send(null); sends the asynchronous request with the only parameter being null which is used for transmitting a POST body if this were a POST request. If sending a POST request, do not forget the Content-Type header which should look something like setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

Finally, document.getElementById("div1").innerHTML = obj.responseText; assigns the value returned by the server to the <div> element with ID="div1"

HTML5: A New Dawn

HTML5 introduced unobtrusive AJAX by defining new data- (data dash) attributes. This has greatly simplified implementing AJAX. Here is an example HTML5 page using the data- attributes:

<!DOCTYPE html>
<head><title>Hello World</title>
<script src="/scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="/scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<div style="float:left;padding:25px;border:1px solid black;border-radius:10px;" id="divHello">
	<a data-ajax="true"
		href="hello.txt">Click here!</a>

This page would look and respond similar to this:



Notice that there is no JavaScript code. It is unobtrusive and all contained in the jQuery scripts added at the top. Upon clicking the link, a connection to the server is opened and a GET request for hello.txt is submitted and the server sends the contents of hello.txt to the web browser to replace the inner HTML of the <DIV> identified as divHello.

The script jquery.unobtrusive-ajax.min.js was added to make all this possible. Upon loading, it hunts the page for data- attributes and then builds the code neccessary to submit and retrieve data to and from the server. jquery.unobtrusive-ajax.min.js requires that the jQuery script be loaded, too.

NOTE: This information is somewhat out of date and needs updating...

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.