Section 1: Introduction

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:
-
Asynchronous
- Sends requests to the server but does not wait for the response
- Does not require a page load
-
JavaScript
- Uses JavaScript HTTP requests
- The XMLHttpRequest is responsible for exchanging data asynchronously with a server and is the most critical piece!
- And
-
XML
- eXtensible Mark-up Language
- XML is covered elsewhere
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.
-
Oddly enough, Ajax doesn't require the use of XML, and it doesn't even have to be asynchronous (as discussed in the following section).
-
JavaScript is required.
- Although Ajax can be used with Java, PHP, jQuery, various JavaScript frameworks like AngularJS, and other languages, Ajax isn't possible without JavaScript because it presupposes JS code running on the client.
- Ajax relies on the XMLHttpRequest object in the browser to request data from the server and JavaScript to display the data.
- If JS is disabled, there's nothing that can execute in the browser and contact the server.
- While the "X" in Ajax stands for XML, alternative approaches such as JavaScript Object Notation (JSON), YAML, EDN, or any similar means of structuring data for interchange can be used to achieve the same results.
-
JavaScript is required.
- That's why the acronym AJAX is now generally just spelled Ajax.
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.
- With synchronous requests, the browser or the code running on the local device makes a request to the server, and then waits for a response from the server.
- Synchronous interactions means that one thing happens after another; the server does not multitask.
- When a user clicks a button, the message is sent to the server, and the response is returned.
-
The user cannot interact with any other page elements until the response is received and the page is updated.
When an asynchronous request is sent to the server, the application continues working rather than waiting for the server to respond.
- Users can still enter data in a Web form, click other buttons, even leave the form.
-
The server quietly responds to the request and when it's finished, it lets the original requestor know that it's done.
- The end result is an application that is responsive, interactive, and feels faster.
One of the biggest advantages that Ajax has is that it can access information on the server without having to reload the web page.
- This means that to retrieve or update one small piece of information, only that information needs to be passed to and from the server instead of having to re-download the entire web page.
Ajax can access the server both synchronously and asynchronously:
- Synchronously, in which the script stops and waits for the server to send back a reply before continuing.
- Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.
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.
- Further, even if a response is delayed — for example, in the case of very large data — site visitors may not realize it because they are occupied elsewhere on the page.
For further explanation, visit When to Use Asynchronous or Synchronous Ajax.
Section 3: Ajax architecture

Section 4: XMLHttpRequest
XMLHttpRequest is the 'core element' of Ajax.
- This element allows a web page to retrieve information from the server without reloading or submitting a page.
- XMLHttpRequest serves as the method of transfer by which it is possible to pull information from an XML document and output it into an HTML document.
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:
- open(): Sets up a new request to a server.
- send(): Sends a request to a server.
- abort(): Bails out of the current request.
- readyState: Provides the current HTML ready state.
- responseText: The text that the server sends back to respond to a request.
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.
- It offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().
-
Using Ajax in jQuery
- Watch jQuery Ajax Tutorial #1 - Using AJAX & APIs
- And be sure to visit How to Use jQuery’s $.ajax() for Asynchronous HTTP Requests
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.
- If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, a JSON MIME type will yield a JavaScript object, a script MIME type will execute the script, and anything else will be returned as a string).
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.
-
The program uses the
$.ajax() method0
with the dataType: "xml" option.$.ajax({
type: "GET",
url: "studentList.xml",
dataType: "xml",The "xml" option for datatype indicates that the request returns an XML Document Object, which is the root of an XML document tree.
-
The error and success settings are specified as follows:
error: function (xhr) {
alert("An error occurred while processing XML file: " + xhr.status + " " + xhr.statusText);
console.log("XML reading Failed: ", xhr);
},
success: function (response) { -
The resulting DOM of the XML file can be manipulated using the .find(selector), which gets any elements below in the DOM that
match the selector.
$(response).find("student").each(function () {
var _lastName = $(this).find('lastName').text();
var _firstName = $(this).find('firstName').text(); - You can find similar examples at JQuery and XML: Using JQuery and Ajax to Process and Read an XML File and Extract and Read Data from an XML file using jQuery and Ajax.
- There are other approaches using Ajax to access data in an XML file, but deciphering those are left to the student.
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:
- 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.
- Add in a try/catch block:
- Try and create the XMLHttpRequest object.
- If that fails (catch (failed)), ensure that request is still set to false.
- Check and see if request is still false (if things worked properly, it won't be).
- 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:
- request-type: The type of request to send. Typical values are GET or POST, but you can also send HEAD requests. The value must always be capitalized. Each one deals with the request in a different way. This link explains the various approaches in detail. W3.Org Protocols
- url: The URL of the file to connect to. Security protocols have made it so that we can't access files from another server, so relative links work just fine.
- asynch: True if you want the request to be asynchronous and false if it should be a synchronous request. This parameter is optional and defaults to true. Remember that if you set it to true, it is asynchronous, and the rest of the code will continue to execute while it sends the request to the server.
- username: If authentication is required, you can specify the username here. This is an optional parameter and has no default value.
- password: If authentication is required, you can specify the password here. This is an optional parameter and has no default value.
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.
- The onreadystatechange property allows you to specify a callback method.
- A callback allows the server to call back into your web page's code.
- It gives a degree of control to the server, as well; when the server finishes a request, it looks in the XMLHttpRequest object and specifically at the onreadystatechange property. Whatever method is specified by that property is then invoked.
- It's a callback because the server initiates calling back into the web page regardless of what is going in the page itself.
- This is actually where the asynchronicity comes into play: The user interacts with a page on one level while on another level, the server answers a request and then fires off the callback method indicated by the onreadystatechange property. So you need to specify that method in your code.
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:
As with almost all cross-browser issues, these ready states are used somewhat inconsistently.
- You might expect to always see the ready state move from 0 to 1 to 2 to 3 to 4, but in practice, that's rarely the case.
- Some browsers never report 0 or 1 and jump straight to 2, then 3, and then 4.
- Other browsers report all states. Still others will report ready state 1 multiple times.
- As you saw in the last example, the server called doSomething() several times and each invocation resulted in an alert box popping up.
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.
- To account for this, the first line in your callback method should be
if (request.readyState == 4)
Click to see the example using request.readyState.
HTTP status codes
HTTP requests also report a status.
- For example, a 404 status indicates that the page referenced by the URL argument in the open() method call does not exist.
- A status code of 200 which simply means okay.
- With a ready state of 4 and a status code of 200, you're ready to process the server's data and that data should be what you requested.
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.
- If the response from the server is not XML, use the responseText property.
- The responseText property returns the response as a string, and you can use it accordingly.
- For instance, one script might return comma-separated values, another pipe-separated values (the pipe is the | character), and another may return one long string of text. It's all up to the server.
- This example uses the responseText property.
- If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property.
- Here is an example:
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("root");
i = 0;
title = (x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue); - When we pull the information in from the XML document, it saves it all as arrays. The poorly named variable i stands in for the index. Where it starts out at 0, it will pull the first set of children tags out of the parent, which we have shortened here to the variable x.
- This sets us up for some cool stuff. If we want to get the next set of children tags, all we have to do is increment the index, we can get the previous one through decrementing i. If we know the set of tags we want to grab, all we have to do is change the index i to that number.
- Another important thing to remember here is that we are using getElementsByTagName to grab the information from the tags. The s in elements is very important.
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
- a function name with NO parameters, or
- an anonymous function
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
- Bandwidth utilization – it saves memory when the data is fetched from the same page.
- More interactive.
- Speedier retrieval of data.
- More can be found in Everything You Need To Know About What is Ajax? Its Importance And Benefits?
Limitations
- Ajax is dependent on JavaScript. If there is some JavaScript problem with the browser or in the OS, Ajax will not work.
- Ajax can be problematic in search engines as it uses JavaScript for most of its parts.
- Source code written in Ajax is easily human readable. There will be some security issues in Ajax.
- Debugging is difficult.
- Increases size of the requests.
- Slow and unreliable network connection.
- Problem with browser back button when using Ajax enabled pages.