What is AJAX?

Some more old notes on AJAX and related stuff

1. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. The term talks about how to asynchronously retrieve data from server using JavaScript and XML, but actually, AJAX goes much beyond that. It is more about providing a rich experience to users. A rich user experience can be simply stated as a ‘desktop application like feel’; now, desktop applications can have the luxury of heavy weight rich User Interfaces and with AJAX the same is possible for web applications, which so far could afford only a basic UI. With AJAX, the need for reloading the UI again and again with every request is gone; we will understand this more in rest of the document.

AJAX in itself is not a language or a framework. It is a technique. It basically uses XMLHTTPRequest Object to fetch the data from server without reloading the page. Additional AJAX supporters are CSS, DOM, DHTML and XSL.

Another keyword you will observe is Asynchronous. Asynchronous communication in general terms means that a browser does not wait for a reply from server once a request is sent. Hence, it does not stop user from interacting with the page while the information is being fetched from server. The data is retrieved as a back ground process and the web page does not get refreshed, the data is displayed dynamically at runtime giving the web application a feel of desktop application and hence improves user experience.

You might question if AJAX is more than just JavaScript and XML, why is it called AJAX? This is what Jesse James Garrett, the man who coined the term AJAX has to say about it “I needed something shorter than ‘Asynchronous JavaScript + CSS + DOM + XMLHttpRequest’ to use when discussing this approach with clients.” hence the term AJAX

2. Where do we use AJAX?

You are already familiar with AJAX if you are a frequent user of internet. Some of the example sites are Flickr, GMail, Hotmail, Google Suggest, or Google Maps. Following uses of AJAX should give you a pretty good picture of what it is capable of doing

2.1. Real time Form Validation: You have a form which asks for your email address. A simple JavaScript will help to check that it has a ‘@’ and a ‘.’ Properly, but what if we want to check that if this email address is already present in database or not. For this we need to hit the server and check the database. Conventionally the operation would refresh the page, but with AJAX the validation can be done at the backend and a message can be shown to the user that the email address is in use without refreshing the page.

2.2. Real time On-Demand Data fetching: You are looking for branches of a bank in a city, there are two columns in the form- City and Address. You provide city and it gives you the addresses. Now one way to achieve this is get all the data regarding all the addresses in all the cities beforehand in the JavaScript. So if bank has 20 branches each in 20 cities, we are fetching 400 records, though user only requests for one city. With AJAX we don’t need to pre-populate our dataset as we can do that once user enters the city name.

2.3. Auto-Completion of text: At some websites you will notice that while you are typing it shows a list of suggestion that is through magic of AJAX. Examples are Google suggest where you get a list of suggestions for the terms which you might want to search or on railway booking site when you are entering name of a place and it autosuggest the station names based on letters you have entered so far.

2.4. Server Push: You are on your email website. The page is open for last 10 mins and now you want to check if you have received any email during that period. Ideally you would refresh the page, but with AJAX it will keep updating the website as and when any emails are revied. A similar example would be a stocks website which keeps displaying latest stock price without any action.

2.5. Rich User Interfaces: As we do not need to upload the UI again and again, we can have the luxury of rich UI. If there are multiple pages in a web application, but the base UI is same for all, AJAX helps sending the UI only once. The next time server will only send the updated contents which would be rendered in the existing UI.

3. Main constituents of AJAX

While working on an AJAX application you will come across the following terms. Combination of one or more of these technologies can be used to create an AJAX application

3.1. DOM

DOM or Document Object Model is a W3C standard set of objects for representing HTML or XML. The DOM model is platform independent and is used by JavaScript to modify and render HTML pages on runtime.

3.2. XML

XML stands for EXtensible Markup Language. It is widely accepted format for transporting and storing of the data. One can create any tags in a way data is required to be saved. It is hierarchical representation of data, where at the top we have parent which will have child nodes and then sub-Childs and so on. We need to parse the XML in order to retrieve the desired data. The following example should help understanding the XML format

<Employees>
<Employee>
<Name>John</Name>
<EmployeeNum>1234</EmployeeNum>
<Designation>PA</Designation>
<Employee>
<Employee>
<Name>Eric</Name>
<EmployeeNum>1232</EmployeeNum>
<Designation>SE</Designation>
<Employee>
<Employee>
<Name>Tim</Name>
<EmployeeNum>1233</EmployeeNum>
<Designation>PM</Designation>
<Employee>
</Employees>

3.3. XMLHttpRequest (XHR)

For AJAX, XMLHttpRequest is the backbone object. It is the technical component that makes the asynchronous server communication possible. The XHR is DOM API which can be used by JavaScript to send and receive data from server from client side. Normally the data fetched is in form of XML, text or JSON.

Creating an Object of XHR is simple. For Browsers like Mozilla, Safari, Opera etc. Use

var request=new XMLHttpRequest();

For Internet Explorer, depending on the version of JavaScript, one of the two would work

Var request= new ActivexObject(‘Microsoft.XMLHTTP’);
Or xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

The following method would give an XHR object for almost all the browser

//For IE
var xmlHttpRequest= false;
try {
xmlHttpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e2) {
xmlHttpRequest = false;
}
}
//For Others
if (!xmlHttpRequest) {
xmlHttpRequest = new XMLHttpRequest();
}

Once we get the XHR object, it provides us following Properties and Methods

Properties

Property Description
onreadystatechange This is an evenlistener property, which is called whenever readyState property changes
readyState This can have following five states
0 = not initialized (open () method not called yet)
1 = loading (send () method not called yet)
2 = loaded (send() method id called, and header and status information is available)
3 = interactive (the responseText property has some partial data)
4 = complete (communication finished)
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
Status Status code returned by server, such as 404 for “Not Found” or 200 for “OK”
statusText String message accompanying the status code

Methods

Method Description
abort() Cancel’s the current request
getAllResponseHeaders() Returns complete set of response headers (labels and values) as a string
getResponseHeader(“headerLabel”) Returns the string value of a single header label
open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]]) Prepares the XHR request by assigning
Method: Get or Post
URL: URL to be called
Asynchronous Flag: Whether the data needs to be sent asynchronously or not
Username: Optional
Password: Optional
send(content) Transmits the request, with the optional content which can be postable string or DOM object data
setRequestHeader(“label”, “value”) Assigns a label/value pair to the header to be sent with a request

3.4. JavaScript

JavaScript is a scripting language, which helps dynamically interacting with HTML pages. It is widely used to do perform runtime form validation checks on the client side.

For AJAX applications, role of JavaScript is very important as this is used to handle events on HTML pages and dynamically updates the contents, which is basis of any Rich Internet applications. Though JavaScript is not the only Scripting language which can be used, but it is the most common and widely used.

3.5. DHTML

DHTML or Dynamic HTML is a combination of multiple technologies like HTML, JavaScript, DOM, and CSS. The purpose of DHTML is to make web pages dynamic and interactive.

According to the World Wide Web Consortium (W3C):
“Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated.”

For example we can update the contents of an HTML page at the runtime like
document.getElementById(id).innerHTML= ‘change it’

3.6. XSL
XSL stands for eXtensible Stylesheet Language is a family of recommendations for defining XML document transformation and presentation. XSL is not directly playing any role with AJAX applications, but in case you try to use XML to create the HTML pages this will come handy.
The XSL family comprises three languages:
XSL Transformations (XSLT): an XML language for transforming XML documents
XSL Formatting Objects (XSL-FO): an XML language for specifying the visual formatting of an XML document
XML Path Language (XPath): a non-XML language used by XSLT, and also available for use in non-XSLT contexts, for addressing the parts of an XML document.

3.7. CSS

CSS or Cascading Style Sheets is the W3C standard style and layout model for HTML. CSS allows web developers to control the style and layout of web pages. It tells the browser how to display various HTML elements, for example what will be font, color, size, alignment of a text or change the display of a button or text on hover. External Style sheets can be created and shared by multiple screens.

4. Different AJAX Formats for Data Transfer

AJAX can send and receive data from server in following formats

4.1. Text

As mentioned above in section 3.3, XMLHttpRequest object has a property called responseText which contains the text returned by Server.

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
document.employeeForm.name.value= xmlHttpRequest.responseText;
}
}

4.2. XML

responseXML property of the XMLHttpRequest contains an XML sent back by the Server

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
parseXML(xmlHttpRequest.responseXML); // we will create this method to parse the XML recieved
}
}

4.3. JSON (JavaScript Object Notion): Well, XML is a very powerful and universally accepted method of representing and handling data. But it is not a human readable format, JSON helps us here. It is a structured format in JavaScript to represent data. A simple example should help understanding; this is the same data which was represented in XML above

Var Employees=
{“Employee”: [
{“name”: “John”, “EmployeeNum”: “1234”, “Designation”: “PA”},
{“name”: “Eric”, “EmployeeNum”: “1232”, “Designation”: “SE”},
{“name”: “Tim”, “EmployeeNum”: “1233”, “Designation”: “PM”},
}

The complex string that is defined above is just an Array, so any information can be easily fetched like getting the name for first employee:

Employees.Employee[0].name;

If the JSON object is in string format, say sent back from server side, it is easy to convert to JSON object usong “eval” method

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
var jsonString = xmlHttpRequest.responseText;
var jsonObject= eval(‘(‘+jsonString+’)’);
}
}

The support for JSON is already available with most of server side programming languages.

5. Server Side Handling

If you look at the XMLHttpRequest object carefully, we are sending a URL in the open method. This URL defines the path to which the request being made is to be forwarded. This means AJAX itself is independent of server side languages. For example if we have an application in which XHR is calling a java servlet to retrieve some XML data, we can simply change the server side to PHP or dot Net by redirecting the URL to the new server. As far as the XML data sent back from that URL is same, AJAX application does not need to care about the server side languages.

Only consideration is that if you are using the XML as data format, then the server side language should have a good support for XML. In case of JSON, we need to take care that server side language has a good support for JSON objects, otherwise we will have to create parsers for the same.

6. A Basic Example

Here is a simple AJAX ‘Hello World’ example. It asks for the name of user, and clicking on the button in HTML page would bring the hello message from Server side without refreshing the page, so all the communication will be happening at the backend using AJAX.

Here is the HTML and JavaScript code.

<html>
<body>
<script type=”text/javascript”>
function ajaxExample()
{
var xmlHttpRequest;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest =new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttpRequest =new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttpRequest =new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4)
{
document.getElementById(“message”).innerHTML= xmlHttpRequest.responseText;
}
}

var name=document.getElementById(“name”).value;

xmlHttpRequest.open(“GET”,”test.jsp?name=”+name,true);
xmlHttpRequest.send(null);
}
</script>
<form name=”AJAXForm”>
Enter Your Name: <input type=”text” id=”name” name=”name” />
<input type=”Button”
onClick=”ajaxExample();” value=”ClickMe” />
<BR></BR>
A Message for you: <label id=”message” name=”message” >Check Here</label>
</form>
</body>
</html>

For this example we will keep a simple jsp file on the server side. The jsp will have following code

<jsp:directive.page contentType=”text/plain”/>

<%
String name=(request.getParameter(“name”)).toString();
String hello= “Hello “+ name;
out.print(hello);
%>

7. AJAX Advantages

* Better User Experience: One of the most important things for the web applications is user experience, as only a satisfied user will come back to your website. In case of AJAX, the user does not have to wait for server response and page refreshes which helps the pages to be more interactive.
* Optimized Bandwidth usage- Server does not have to send UI related information again and again, just the contents are sent. In many cases, related pages on a website consist of much content that is common between them. Using traditional methods, that content would have to be reloaded on every request. However, using Ajax, a web application can request only the content that needs to be updated, thus drastically reducing bandwidth usage and load time.
* No Special setup: Unlike Applets or Flash files, where you need to install plug-ins for running the applications, AJAX just need JavaScript enabled browser, which is common.
* Rich User Interfaces: The use of asynchronous requests allows the client’s Web browser UI to be more interactive and to respond quickly to inputs, and sections of pages can also be reloaded individually. Users may perceive the application to be faster or more responsive, even if the application has not changed on the server side.

8. AJAX Disadvantages

* No Standards as yet- The lack of a standards body behind Ajax means there is no widely adopted best practice to test Ajax applications.
* Back button not handled- Pages dynamically created using successive Ajax requests do not automatically register themselves with the browser’s history engine, so clicking the browser’s “back” button may not return the user to an earlier state of the Ajax-enabled page, but may instead return them to the last full page visited before it. Workarounds include the use of invisible IFrames to trigger changes in the browser’s history and changing the anchor portion of the URL (following a #) when AJAX is run and monitoring it for changes.
* Search Engines: Most of the search engines do not look for JavaScript code; hence the web applications using AJAX should provide an alternative means of accessing the content in order to get listed properly.
* Debugging: Debugging of JavaScript can be tougher than debugging any server side language.
* Security: You can view client-side JavaScript technology simply by selecting View Source from an Ajax-enabled HTML page. If we are handling any sensitive data in an AJAX application, that would show up with JavaScript. This needs to be taken care of while creating AJAX applications