Tag Archives: AJAX

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

Prototype.js library

Some of my old notes from Prototype (3-4 yrs older so there might be changes)

Overview

Prototype is a JavaScript toolkit. This helps in generation of a application by providing commonly used functionality so that the developer does not have to spend time on them.

The Prototype JS has features provides some basic functions which work as short cuts to already existing functionalities e.g. $() can be used in place of document.getElementById(), there are other complex functions for dealing with XMLHttpRequest. A many other libraries are created by extending this library.

You can download the free prototype.js from http://www.prototypejs.org/download. Once downloaded this JavaScript file can be added to any HTML page just like any other JavaScript file <script type=”text/javascript” src=”prototype.js”></script>

Key Functionalities

Let us look at some of the major functionalities provided by Prototype which makes life of developer simple.

$():

This is equivalent to saying document.getElemetById()
e.g.
var name=$(‘name’);

is same as
var name=document.getElementByID(‘name’);

Where HTML has
<input type= “text” id= “name” value= “John”/>

$$():

This will return you an array of elements from HTML document
e.g.
var eleArray= $$(“#formName input”);

This would return an array of all input type fields inside the form formName. This can be further used like

for(var i=0; i<eleArray.length; i++)
{
valueArray=eleArray[i].value;
}

$F():

To get the value of an element in the page
$F(‘name’) is equivalent to document.getElementByID(‘name’).value;

$A():

$A() Creates an array
var arrayOfNodes= $A(xmldoc.getElementsByTagName(‘abc’));

$H():

$H() Creates a hash table
var employeeHash= $H({
name: “John”,
email: “John@company.com”,
employeeId: “12345”
});

Try.these() Function:

This is an interesting function which lets developer write multiple functions. The code keep trying executing functions until one of them is success. This can be helpful if we are writing code to be supported by multiple versions of JavaScript or multiple browsers

Try.these(
function() {//do something
alert (“first one worked”);
return;
},
function() { // do something
alert (“second one worked”);
return;
}

AJAX Object:

Prototype provides AJAX object to minimize the effort using any AJAX related methods. AJAX object further provides the following classes.

AJAX.Request:

Ajax.Request object encapsulates the commonly used Ajax code for setting up the XMLHttpRequest object, performing cross-browser checking for compatibility and callback handling.

function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
onSuccess: process,
onFailure: function() {
alert(“There was an error with the connection”);
}
});
}

AJAX.Updater:

This is similar to the AJAX.Rrquest method above, with an additional feature that it can also update the page with the information returned by server to AJAX call.
new Ajax.Updater(container, url[, options])
function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
‘placeholder’,
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
}
});
}

AJAX.Responders:

AJAX responders are more of global methods which we register and unregister at the start and end of execution of code. They monitor all the AJAX activity going on and show the processing activities (say some animation while the data is being fetched from the server).
Ajax.Responders.register(attributes)
Ajax.Responders.unregister(attributes)
Some of the most common callbacks which are used with responders is
Ajax.Responders.register({
onCreate: showProcessing,
onComplete: hideProcessing
});

Additional Links

http://www.prototypejs.org/
http://www.sergiopereira.com/articles/prototype.js.html
http://attic.scripteka.com/prototype_cheatsheet_1.6.0.2.pdf
http://particletree.com/features/quick-guide-to-prototype/

AJAX with Java

As a major requirement for AJAX application from server side language is to retrieve the request from client side and then parse it based on the format of the request. The request can be in form of a simple string, or XML, or JSON. And similarly the AJAX application expects a response back from server in one of these formats. Java can fulfill these requirements easily.

As for the first part, the server side language needs to accept the request from AJAX application in client side. Now Java has multiple ways to accept the request like JSPs, Servlets, Struts, JSFs etc. lets take a Servlet example

Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
String ajaxData=req.getParameter(“Data”);
String returnString = executeAJAXRequest(ajaxData);
res.setContentType(“text/xml”);
res.getWriter.write(returnString);
}

Above one is a simple example. I left some of the details on purpose. Like what is executeAJAXRequest method doing. This will actually depend on the kind of request we receive.

The request might be a text based one where we don’t need to do any special parsing.

String executeAJAXRequest(String name)
{
String helloString= “Hello “+name;
return helloString;
}

That’s just a simple example; we could be doing some database operations in the method based on the name we got. But the idea is that the data is being used as it is. If it was a number say employee number we would convert to long and use.

Now if the data is in XML format. We already know that Java has strong XML support. It can parse and create XML documents easily using either DOM or SAX parsers. The following example shows how to parse data (uses apache’s xerces library)

ajaxRequest=”<employees><employee><name>John</name></employee></employees>”;

ArrayList executeAJAXRequest(String ajaxRequest)
{
ArrayList<String> nameValueArray=new ArrayList<String>(10);
try
{
DOMParser parser = new DOMParser();

parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(ajaxRequest)));
DocumentImpl document = (DocumentImpl)parser.getDocument();

//get the root of the XML document
Node root = document.getFirstChild();
NodeList childNodes=root.getChildNodes();

for(int i=0;i<childNodes.getLength();i++)
{
nameValueArray.add(i, childNodes.item(i).getFirstChild().getFirstChild().getNodeValue());
}
}
catch (SAXException e)
{
e.printStackTrace();
//handle exception
}
catch(IOException e)
{
e.printStackTrace();
//handle exception
}

return nameValueArray;
}

The third way to pass data from client to server and vice versa is by using JSON. There are many libraries available in Java to parse and create JSON strings. Here is an example of code parsing a JSON String from client side using json-simple library (http://code.google.com/p/json-simple )

JSON string received from client is something like “{\”Employee\”: [{\”name\”: \”Eric\”, \”EmployeeNum\”: \”1232\”, \”Designation\”: \”SE\”}]}”

void executeAJAXRequest(String ajaxRequest)
{
JSONParser jsonParser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){

public List creatArrayContainer() {
//Add Details if required
return null;
}

public Map createObjectContainer() {
//Add Details if required
return null;
}
};

try{
Map jsonMap1 = (Map)jsonParser.parse(ajaxRequest, containerFactory);

Iterator iter1 = jsonMap1.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry entry1 = (Map.Entry)iter1.next();
String valueString=entry1.getValue().toString();
String dataString=valueString.substring(1,valueString.length()-1);

Map jsonMap2 = (Map)jsonParser.parse(dataString, containerFactory);

Iterator iter2 = jsonMap2.entrySet().iterator();
System.out.println(“Here are the Employee Details”);
while(iter2.hasNext()){
Map.Entry entry2 = (Map.Entry)iter2.next();
System.out.println(entry2.getKey() + “=>” + entry2.getValue());
}
}

}
catch(ParseException pe){
System.out.println(pe);
}
}

ZK framework: AJAX without JavaScript

Recently came across ZK framework which can be used to create AJAX based UI without actual JavaScript code. It claims that you do not need to be a programmer to code using ZK framework which actually uses ZUML Markup language to do create the UI. I have not used it yet but look interesting and would like to give it a try.

http://en.wikipedia.org/wiki/ZK (framework)

http://www.zkoss.org/

jQuery error- simpleLightbox not found

Faced a unique error with jQuery today.  I was using jquery-1.3.2.min.js and jquery-simplelightbox.js. Which were included properly in the jsp file, but still the javascript was throwing the error that simpleLightbox function is not found.

on a close look it was found that after adding both the JS files, an additional jsp file was added which was again adding jquery-1.3.2.min.js, hence overriding the original jQuery object.

Lesson learnt- Always make sure that jQuery js file is added only once, especially if we are modifying the object.