Ajax



index
Disabled back button Next Section
printable version

Section 1: Introduction
Ajax logo.

Ajax, sometimes written as AJAX (shorthand for asynchronous JavaScript and XML), is a group of interrelated web development techniques used on the client-side to create interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive animation on web pages and better quality of Web services thanks to the asynchronous mode. Data is retrieved using the XMLHttpRequest object. Despite the name, the use of JavaScript and XML is not actually required, nor do the requests need to be asynchronous.

from Ajax (programming) - Wikipedia

Ajax originally stood for Asynchronous JavaScript and XML:


Ajax is a collection of techniques that allows web pages to be updated asynchronously, which means that the browser doesn't need to reload the entire page when only a small bit of data on the page has changed.

Ajax is useful because it lets developers build more interactive pages. Consider your Twitter feed. Your feed can update without having to refresh the page. You’ll notice new Tweets appear when you keep scrolling. This is the sort of behavior enabled by Ajax.

Other examples include Google Maps or Google autocomplete.

from Ajax: Courses, Training, and Other Resources

Since DOM was a recent topic, you may be wondering whether it has any role in Ajax. DOM is an application programming interface (API) for accessing and manipulating structured documents and it represents the structure of HTML (and XML) documents. In a basic Ajax request, a user clicks on something, the Ajax request gets sent, and a part of the DOM gets updated without the entire page reloading.

Section 2: Asynchronous

Standard web applications process interactions between web visitors and the server synchronously.

When an asynchronous request is sent to the server, the application continues working rather than waiting for the server to respond.

One of the biggest advantages that Ajax has is that it can access information on the server without having to reload the web page.

Ajax can access the server both synchronously and asynchronously:

Processing a request asynchronously avoids the delay while the retrieval from the server takes place because your visitor can continue to interact with the web page; the requested information will be processed in the background and the response will update the page as and when it arrives.

For further explanation, visit When to Use Asynchronous or Synchronous Ajax.

Section 3: Ajax architecture
Ajax architecture.
Section 4: XMLHttpRequest

XMLHttpRequest is the 'core element' of Ajax.

You can issue an XMLHttpRequest from JavaScript, or by using a jQuery method.

Here are just a few of the methods and properties available in JavaScript for use on this object:

Each of these methods and properties relate to sending a single request and dealing with a response.

For security reasons, modern browsers do not allow access across domains, which means that both the web page and the XML file it tries to load must be located on the same server.

Here are a few examples. Look at the source code, and notice that there is no data in the page itself. It all comes from an xml file.

Using Ajax in jQuery is the topic of an upcoming section.

Section 5: jQuery

Different browsers implement the Ajax API differently, which typically meant that developers had to account for all the different browsers to ensure that Ajax would work universally.

Fortunately, jQuery provides Ajax support that abstracts away unforeseen browser differences.


jQuery.ajax( url [, settings ] )

jQuery.ajax() performs an asynchronous HTTP (Ajax) request.

The most thorough discussion of this method can be found at jQuery API Documentation: jQuery.ajax().

The dataType setting indicates type of data that you're expecting back from the server.

The error setting specifies a function to be invoked if the request fails.

The success setting specifies a function to be invoked if the request succeeds, and is where the retrieved data is accessed and manipulated.

Here is a demo that uses jQuery methods to access an XML file for data to populate a page. Be sure to view the .js file.

Here is the 4430 professor's PowerPoint presentation on additional Ajax concepts:

Section 6: Step-by-step with JavaScript (Optional)

Step 1: Instantiate XMLHttpRequest Object

First, you need to create a new variable and assign it to an instance of XMLHttpRequest object. That's pretty simple in JavaScript; you just use the new keyword with the object name:

var request = new XMLHttpRequest();

At that point, you're ready to use the object in your functions.

Error Handling

Things can go wrong and this code doesn't provide any error-handling, so a better approach is to create this object and have it gracefully fail if something goes wrong.

Older browsers don't support XMLHttpRequest and you need to let those users know that something has gone wrong by generating a JavaScript alert:

var request = false;
try
{
request = new XMLHttpRequest();
}
catch (failed)
{
request = false;
}

if (!request)
alert("Error initializing XMLHttpRequest! Your browser may not support Ajax.");

Try block: attempt to try something

Catch block: what happens if try fails

Just to be sure you understand every step, here is a detailed explanation:

  1. Create a new variable called request and assign it a false value. Using false as a condition means the XMLHttpRequest object hasn't been created yet.
  2. Add in a try/catch block:
    1. Try and create the XMLHttpRequest object.
    2. If that fails (catch (failed)), ensure that request is still set to false.
  3. Check and see if request is still false (if things worked properly, it won't be).
  4. If there was a problem (and request is false), use an alert to inform users there was a problem.

Step 2: Configure the Request

We next utilize the open() method of the XMLHttpRequest object to configure the request.

The open() method must be called by the variable that we associated with the XMLHttpRequest.

request.open("GET","file.xml",true);

The open() method takes as many as five parameters:

Note that open() is poorly named, because it doesn't really open anything. It simply associates a file name and request type with the request object specified earlier.


Step 3: Send the request

Once you configure the request with open(), you're ready to send the request to the server for processing using the send() method.

send() takes only a single parameter, the content to send.

Typically if the method is GET then the parameter will be null or an empty string, or the method will be called without any parameters.

request.send(null);


Step 4: React to Server State Change

The power of Ajax revolves around a simple property of XMLHttpRequest called onreadystatechange.

So far, we have configured a request and sent it to the server. If it is an asynchronous request, the web page will not wait for the server; rather the code that made the request will continue, and perhaps even exit.

The server also needs to be given some type of instruction on what to do when it's finished processing the request sent to it by XMLHttpRequest, and this is where the onreadystatechange property comes into play.

request.onreadystatechange = doSomething;

In fact, the code so far looks like the following. (Assume the request is established in the body onLoad event.)

function doSomething()
{
alert("Server is done!");
}

function testing()
{
request.open("GET", "test.xml", true);
request.onreadystatechange=doSomething; // Note that the function call has no parentheses.
request.send(null);
}

Pay close attention to where in the code this property is set — it's before send() is called. You must set this property before the request is sent, so the server can look up the property when it finishes answering a request.

Note the lack of parentheses in the onreadystatechange line. More on this in the next section.

You can test the page and view the code here.

Notice that something seems a bit off – the alert pops up multiple times.

We explained that the server, once finished with a request, looks up what method to call in the onreadystatechange property of XMLHttpRequest. However, it calls that method every time the HTTP ready state changes, and there are several states.

HTTP ready states

An HTTP ready state indicates the state or status of a request.

It's used to figure out if a request has been started, if it's being answered, or if the request/response model has completed.

It's also helpful in determining whether it's safe to read whatever response text or data that a server might have supplied.

Here are the ready states: Table 7

As with almost all cross-browser issues, these ready states are used somewhat inconsistently.

For Ajax programming, the only state you need to deal with directly is ready state 4, indicating that a server's response is complete and it's safe to check the response data and use it.

Click to see the example using request.readyState.

HTTP status codes

HTTP requests also report a status.

The first line in your callback method should be modified to read

if (request.readyState==4 && request.status==200)

Click to see the example using request.status.


Step 5: Process Data Upon Server Response

Once you made sure the request was completely processed (through the ready state) and the server returns an okay response (through the status code), you can deal with the data sent back by the server.

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.


Here are some examples that use responseXML.

Section 7: Tips and Traps using Ajax with JavaScript (Optional)

This section will point out a few quirks that newbies often overlook.

send()

Remember that the send method is called after the onreadystatechange property is set. That was pointed out in the previous section, but bears repeating.


onreadystatechange functions

The function used to set the onreadystatechange property can be

Why? There can be no parentheses after the function name and no parameters passed because you're simply assigning a reference to the function, rather than immediately calling it.

Or, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous functions") and define the actions that will process the response.

Functions can be assigned to variables and then using that variable, the function can be called. That is what happens here. You are not calling a function, but rather assigning a function to a class member. When request.send(null) is called, it invokes that function. All of this falls into the realm of anonymous functions and is extremely prevalent in event-style Object-Oriented Programming. It is similar to using void* in C to hold a function in a variable. It is similar to lambda in python, Java, or C#.

More here.


Returning values from functions associated with onreadystatechange

What if you want the aforementioned function to return a value that can be used when the ready state changes?

It can't. Your onreadystatechange handler gets called long after the function returns.

Remember – we're dealing with asynchronicity, i.e., functions that generate their return value not immediately, but after a certain asynchronous process.

To deal with this, one has to use a callback to provide return value. Refer to this link.


Can't we even pass parameters to an onreadystatechange function?

Sure, but your anonymous function will have to call a different function that will accept parameters.

Read Ajax: Passing parameters to onreadystatechange function.


Don't forget!

If you overlook any of these quirks, your web page will not work correctly. The "voice of experience" speaks!

Section 8: Benefits and Limitations

Benefits

Limitations