Skip to main content

AJax


AJAX = Asynchronous JavaScript and XML

AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications.
With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.

AJAX is based on Internet standards

AJAX is based on the following web standards:
  • JavaScript
  • XML
  • HTML
  • CSS
lamp AJAX applications are browser and platform independent.

AJAX is about better Internet-applications

Internet-applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.
However, Internet-applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer and more user-friendly.

AJAX uses the XMLHttpRequest object

To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object
With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

The XMLHttpRequest object

By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!
AJAX was made popular in 2005 by Google (with Google Suggest).
Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).

Your first AJAX application

To understand how AJAX works, we will create a small AJAX application.
First we are going to create a standard HTML form with two input fields: Name and Time. The "Name" field will be filled out by the user, and the "Time" field will be filled out with AJAX.
The HTML file will be named "testAjax.htm", and it looks like this (notice that the HTML form below has no submit button!):
<form name="myForm">

Name: <input name="username" type="text">

Time: <input name="time" type="text">

</form>

The next chapters will explain the keystones of AJAX.

AJAX - Browser support

The keystone of AJAX is the XMLHttpRequest object.
All new browsers use the built-in JavaScript XMLHttpRequest object to create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).
Let's update our "testAjax.htm" file with a JavaScript that creates an XMLHttpRequest object:

<html>

<body>



<script type="text/javascript">

function ajaxFunction()

{

var xmlhttp;

if (window.XMLHttpRequest)

{

// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

else

{

alert("Your browser does not support XMLHTTP!");

}

}

</script>



<form name="myForm">

Name: <input type="text" name="username" />

Time: <input type="text" name="time" />

</form>



</body>

</html>

Example explained

1. Create a variable named xmlhttp to hold the XMLHttpRequest object.
2. Try to create the XMLHttpRequest object with xmlhttp=new XMLHttpRequest().
3. If that fails, try xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"). This is for IE6 and IE5.
4. If that fails too, the user has a very outdated browser, and will get an alert stating that the browser doesn't support XMLHTTP.
Note: The code above can be used every time you need to create an XMLHttpRequest object, so just copy and paste it whenever you need it.
The next chapter shows how to use the XMLHttpRequest object to communicate with a server.

AJAX - More about the XMLHttpRequest object

Before sending data off to a server, we will look at three important properties of the XMLHttpRequest object.

The onreadystatechange property

After a request to a server, we need a function to receive the data returned from the server.
The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.
The following code sets the onreadystatechange property and stores an empty function inside it:
xmlhttp.onreadystatechange=function()
{
// We are going to write some code here
}


The readyState property

The readyState property holds the status of the server's response.
Each time the readyState property changes, the onreadystatechange function will be executed.
Possible values for the readyState property:
StateDescription
0The request is not initialized
1The request has been set up
2The request has been sent
3The request is in process
4The request is complete
Add an If statement to the onreadystatechange function to test if the response is complete (means that now we can get our data):
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
// Get data from the server's response
}
}


The responseText property

The data sent back from a server can be retrieved with the responseText property.
Now, we want to set the value of the "Time" input field equal to responseText:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.myForm.time.value=xmlhttp.responseText;
}
}
The next chapter shows how to ask a server for data!

AJAX - Sending a request to a server

To send off a request to the server, we use the open() and send() methods.
The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously.
The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:
xmlhttp.open("GET","time.asp",true);
xmlhttp.send(null);
Now we must decide when the AJAX function should be executed.
We will let the function run "behind the scenes" when a user types something in the "Name" field:

<form name="myForm">

Name: <input type="text" name="username" onkeyup="ajaxFunction();" />

Time: <input type="text" name="time" />

</form>



<html>

<body>



<script type="text/javascript">

function ajaxFunction()

{

var xmlhttp;

if (window.XMLHttpRequest)

{

// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

else

{

alert("Your browser does not support XMLHTTP!");

}

xmlhttp.onreadystatechange=function()

{

if(xmlhttp.readyState==4)

{

document.myForm.time.value=xmlhttp.responseText;

}

}

xmlhttp.open("GET","time.asp",true);

xmlhttp.send(null);

}

</script>



<form name="myForm">

Name: <input type="text" name="username" onkeyup="ajaxFunction();" />

Time: <input type="text" name="time" />

</form>



</body>

</html>









Introducing Asynchronous JavaScript Technology and XML (Ajax)
Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch content that may be formatted as XML documents, HTML content, plain text, or JavaScript Object Notation (JSON). The JavaScript technology may then use the content to update or modify the Document Object Model (DOM) of the HTML page. The term Asynchronous JavaScript Technology and XML (Ajax) has emerged recently to describe this interaction model.
Ajax is not new. These techniques have been available to developers targeting Internet Explorer on the Windows platform for many years. Until recently, the technology was known as web remoting or remote scripting. Web developers have also used a combination of plug-ins, Java applets, and hidden frames to emulate this interaction model for some time. What has changed recently is the inclusion of support for the XMLHttpRequest object in the JavaScript runtimes of the mainstream browsers. The real magic is the result of the JavaScript technology's XMLHttpRequest object. Although this object is not specified in the formal JavaScript technology specification, all of today's mainstream browsers support it. The subtle differences with the JavaScript technology and CSS support among current generation browsers such as Mozilla Firefox, Internet Explorer, and Safari are manageable. JavaScript libraries such as Dojo, Prototype, and the Yahoo User Interface Library have emerged to fill in where the browsers are not as manageable and to provide a standardized programming model. Dojo, for example, is addressing accessibility, internationalization, and advanced graphics across browsers -- all of which had been thorns in the side of earlier adopters of Ajax. More updates are sure to occur as the need arises.
What makes Ajax-based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the loading of a document, a mouse click, focus changes, or even a timer. Ajax interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces to be displayed. Ajax will require a different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component.
Some uses for Ajax interactions are the following:
  • Real-time form data validation: Form data such as user IDs, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form. See Realtime Form Validation for details.
  • Autocompletion: A specific portion of form data such as an email address, name, or city name may be autocompleted as the user types.
  • Load on demand: Based on a client event, an HTML page can fetch more data in the background, allowing the browser to load pages more quickly.
  • Sophisticated user interface controls and effects: Controls such as trees, menus, data tables, rich text editors, calendars, and progress bars allow for better user interaction and interaction with HTML pages, generally without requiring the user to reload the page.
  • Refreshing data and server push: HTML pages may poll data from a server for up-to-date data such as scores, stock quotes, weather, or application-specific data. A client may use Ajax techniques to get a set of current data without reloading a full page. Polling is not the most effecient means of ensuring that data on a page is the most current. Emerging techniques such as Comet are being developed to provide true server-side push over HTTP by keeping a persistent connection between the client and server. See this blog entry on Comet using Grizzly for more on the development of server push with Java technology.
  • Partial submit: An HTML page can submit form data as needed without requiring a full page refresh.
  • Mashups: An HTML page can obtain data using a server-side proxy or by including an external script to mix external data with your application's or your service's data. For example, you can mix content or data from a third-party application such as Google Maps with your own application.
  • Page as an application: Ajax techniques can be made to create single-page applications that look and feel much like a desktop application. See the article on the use of Ajax and portlets for more on how you can use portlet applications today.
Though not all-inclusive, this list shows that Ajax interactions allow web applications to do much more than they have done in the past.
The Anatomy of an Ajax Interaction
Now that we have discussed what Ajax is and what some higher-level issues are, let's put all the pieces together and look at an Ajax-enabled Java application.
Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
Ajax Interaction

Figure 1: An Ajax Interaction Provides Validation Logic
The following items represent the setups of an Ajax interaction as they appear in Figure 1.
  1. A client event occurs.
  2. An XMLHttpRequest object is created and configured.
  3. The XMLHttpRequest object makes a call.
  4. The request is processed by the ValidateServlet.
  5. The ValidateServlet returns an XML document containing the result.
  6. The XMLHttpRequest object calls the callback() function and processes the result.
  7. The HTML DOM is updated.
Now let's look at each step of the Ajax interaction in more detail.
1. A client event occurs.
JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component.

<input type="text"

       size="20"

         id="userid"

       name="id"

    onkeyup="validate();">

This form element will call the validate() function each time the user presses a key in the form field.
2. A XMLHttpRequest object is created and configured.
An XMLHttpRequest object is created and configured.

var req;



function validate() {

var idField = document.getElementById("userid");

var url = "validate?id=" + encodeURIComponent(idField.value);

if (typeof XMLHttpRequest != "undefined") {

  req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

  req = new ActiveXObject("Microsoft.XMLHTTP");

}

req.open("GET", url, true);

req.onreadystatechange = callback;

req.send(null);

}




The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
3. The XMLHttpRequest object makes a call.
When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter.
Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:


req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

req.send("id=" + encodeURIComponent(idTextField.value));




When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
4. The request is processed by the ValidateServlet.
A servlet mapped to the URI "validate" checks whether the user ID is in the user database.
A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken.

public class ValidateServlet extends HttpServlet {



private ServletContext context;

private HashMap users = new HashMap();



public void init(ServletConfig config) throws ServletException {

   super.init(config);

   this.context = config.getServletContext();

   users.put("greg","account data");

   users.put("duke","account data");

}



public void doGet(HttpServletRequest request, HttpServletResponse  response)

   throws IOException, ServletException {



   String targetId = request.getParameter("id");



   if ((targetId != null) && !users.containsKey(targetId.trim())) {

       response.setContentType("text/xml");

       response.setHeader("Cache-Control", "no-cache");

       response.getWriter().write("<message>valid</message>");

   } else {

       response.setContentType("text/xml");

       response.setHeader("Cache-Control", "no-cache");

       response.getWriter().write("<message>invalid</message>");

   }

}

}




In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
5. The ValidateServlet returns an XML document containing the results.
The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the response.


response.setContentType("text/xml");

response.setHeader("Cache-Control", "no-cache");

response.getWriter().write("invalid");



The developer must be aware of two things. First, the Content-Type must be set to text/xml. Second, the Cache-Control must be set to no-cache. The XMLHttpRequest object will process only requests that are of the Content-Type of only text/xml, and setting Cache-Control to no- cache will keep browsers from locally caching responses for cases in which duplicate requests for the same URL (including URL parameters) may return different responses.
6. The XMLHttpRequest object calls the callback() function and processes the result.
The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction.




function callback() {

if (req.readyState == 4) {

   if (req.status == 200) {

       // update the HTML DOM based on whether or not message is valid

   }

}

}


Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded.
Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.




<message>

valid

</message>


This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user:




function parseMessage() {

var message = req.responseXML.getElementsByTagName("message")[0];

setMessage(message.childNodes[0].nodeValue);

}



The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
7. The HTML DOM is updated.
JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById("userIdMessage"), where "userIdMessage" is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements.
One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.


<script type="text/javascript">



...



function setMessage(message) {

var mdiv = document.getElementById("userIdMessage");

if (message == "invalid") {

  mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</ div>";

} else {

  mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</ div>";

}

}

</script>

<body>

<div id="userIdMessage"></div>

</body>








The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applications.

Final Thoughts
Although many of these benefits are noteworthy, this approach has some challenges as well:
  • Complexity: Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic to generate the XML content needed by the client HTML pages. HTML page developers need to have a basic understanding of JavaScript technology to create new Ajax functionality. Other options such as Project jMaki and Project Dynamic Faces provide a way for Java developers to better use Ajax functionality without requiring deep knowledge of JavaScript technology.
  • Standardization of the XMLHttpRequest object: The XMLHttpRequest object is not yet part of the JavaScript technology specification, which means that the behavior may vary depending on the client. It's best to use libraries such as Dojo, which provides fallback solutions for making Ajax interactions transparently even on older browsers that do not support the XMLHttpRequest Object:.
  • JavaScript technology implementations: Ajax interactions depend heavily on JavaScript technology, which has subtle differences depending on the client. See QuirksMode.org for more details on browser-specific differences. Consider using a library such as Dojo, which addresses many of the differences.
  • Debugging: Ajax applications are also difficult to debug because the processing logic is embedded both in the client and on the server. Browser add-ons such as Mozilla Firebug have emerged to make debuging easier. Frameworks such as the Google Web Toolkit have emerged to allow for client and server round-trip debugging.
  • Securing resources and protecting your data: You can view client-side JavaScript technology simply by selecting View Source from an Ajax-enabled HTML page. A poorly designed Ajax-based application could open itself up to hackers or plagiarism. When providing Ajax services, you should take care to make sure that those services are made available only to those intended. See Restricting Access to Your Ajax Services for more information on protecting your services.

Should I consider AJAX?

AJAX definitely has the buzz right now, but it might not be the right thing for you. AJAX is limited to the latest browsers, exposes browser compatibility issues, and requires new skill-sets for many. There is a good blog entry by Alex Bosworth on AJAX Mistakes which is a good read before you jump full force into AJAX.
On the other hand you can achieve highly interactive rich web applications that are responsive and appear really fast. While it is debatable as to whether an AJAX based application is really faster, the user feels a sense of immediacy because they are given active feedback while data is exchanged in the background. If you are an early adopter and can handle the browser compatibility issues, and are willing to learn some more skills, then AJAX is for you. It may be prudent to start off AJAX-ifying a small portion or component of your application first. We all love technology, but just remember the purpose of AJAX is to enhance your user's experience and not hinder it.

Does AJAX work with Java?

Absolutely. Java is a great fit for AJAX! You can use Java Enterprise Edition servers to generate AJAX client pages and to serve incoming AJAX requests, manage server side state for AJAX clients, and connect AJAX clients to your enterprise resources. The JavaServer Faces component model is a great fit for defining and using AJAX components.

Won't my server-side framework provide me with AJAX?

You may be benefiting from AJAX already. Many existing Java based frameworks already have some level of AJAX interactions and new frameworks and component libraries are being developed to provide better AJAX support. I won't list all the Java frameworks that use AJAX here, out of fear of missing someone, but you can find a good list at www.ajaxpatterns.org/Java_Ajax_Frameworks.
If you have not chosen a framework yet it is recommended you consider using JavaServer Faces or a JavaServer Faces based framework. JavaServer Faces components can be created and used to abstract many of the details of generating JavaScript, AJAX interactions, and DHTML processing and thus enable simple AJAX used by JSF application developer and as plug-ins in JSF compatible IDE's, such as Sun Java Studio Creator.

Where should I start?

Assuming the framework you are using does not suffice your use cases and you would like to develop your own AJAX components or functionality I suggest you start with the article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition.
If you would like to see a very basic example that includes source code you can check out the tech tip Using AJAX with Java Technology. For a more complete list of AJAX resources the Blueprints AJAX Home page.
Next, I would recommend spending some time investigating AJAX libraries and frameworks. If you choose to write your own AJAX clients-side script you are much better off not re-inventing the wheel.
AJAX in Action by Dave Crane and Eric Pascarello with Darren James is good resource. This book is helpful for the Java developer in that in contains an appendix for learning JavaScript for the Java developer.

What do I need to know to create my own AJAX functionality?

If you plan not to reuse and existing AJAX component here are some of the things you will need to know.
Plan to learn Dynamic HTML (DHTML), the technology that is the foundation for AJAX. DHTML enables browser-base realtime interaction between a user and a web page. DHTML is the combination of JavaScript, the Document Object Model (DOM) and Cascading Style Sheets (CSS).
  • JavaScript - JavaScript is a loosely typed object based scripting language supported by all major browsers and essential for AJAX interactions. JavaScript in a page is called when an event in a page occurs such as a page load, a mouse click, or a key press in a form element.
  • DOM - An API for accessing and manipulating structured documents. In most cases DOM represent the structure of XML and HTML documents.
  • CSS - Allows you to define the presentation of a page such as fonts, colors, sizes, and positioning. CSS allow for a clear separation of the presentation from the content and may be changed programmatically by JavaScript.
Understanding the basic request/response nature of HTTP is also important. Many subtle bugs can result if you ignore the differences between the GET and OIst methods when configuring an XMLHttpRequest and HTTP response codes when processing callbacks.
JavaScript is the client-side glue, in a sense. JavaScript is used to create the XMLHttpRequest Object and trigger the asynchronous call. JavaScript is used to parse the returned content. JavaScript is used to analyze the returned data and process returned messages. JavaScript is used to inject the new content into the HTML using the DOM API and to modify the CSS.

Do I really need to learn JavaScript?

Basically yes if you plan to develop new AJAX functionality for your web application.
On the other hand, JSF components and component libraries can abstract the details of JavaScript, DOM and CSS. These components can generate the necessary artifacts to make AJAX interactions possible. Visual tools such as Java Studio Creator may also use AJAX enabled JSF components to create applications, shielding the tool developer from many of the details of AJAX. If you plan to develop your own JSF components or wire the events of components together in a tool it is important that you have a basic understanding of JavaScript. There are client-side JavaScript libraries (discussed below) that you can call from your in page JavaScript that abstract browser differences. Object Hierarchy and Inheritance in JavaScript is a great resource for a Java developer to learn about JavaScript objects.

What JavaScript libraries and frameworks are available?

There are many libraries/frameworks out there (and many more emerging) that will help abstract such things as all the nasty browser differences. Three good libraries are The Dojo Toolkit, Prototype, and DWR.
  • The Dojo Toolkit contains APIs and widgets to support the development of rich web applications. Dojo contains an intelligent packaging system, UI effects, drag and drop APIs, widget APIs, event abstraction, client storage APIs, and AJAX interaction APIs. Dojo solves common usability issues such as support for dealing with the navigation such as the ability to detect the browser back button, the ability to support changes to the URL in the URL bar for bookmarking, and the ability to gracefully degrade when AJAX/JavaScript is not fully support on the client. Dojo is the Swiss Army Knife of JavaScript libraries. It provides the widest range of options in a single library and it does a very good job supporting new and older browsers.
  • Prototype focuses on AJAX interactions including a JavaScript AJAX object that contains a few objects to do basic tasks such as make a request, update a portion of a document, insert content into a document, and update a portion of a document periodically. Prototype JavaScript library contains a set of JavaScript objects for representing AJAX requests and contains utility functions for accessing in page components and DOM manipulations. Script.aculo.us and Rico are built on top of Prototype and provide UI effects, support for drag and drop, and include common JavaScript centric widgets. If you are just looking to support AJAX interactions and a few basic tasks Prototype is great. If you are looking for UI effects Rico and Script.aculo.us are good options.
  • Yahoo UI Library is a utility library and set of widgets using the APIs to support rich clients. The utility library includes support for cross-browser AJAX interactions, animation, DOM scriptging support, drag and drop, and cross browser event support. The Yahoo UI Library is well documnented and contains many examples.
  • DWR (Dynamic Web Remoting) is a client-side and server-side framework that focuses on allowing a developer to do RPC calls from client-side JavaScript to plain old Java objects in a Java Enterprise Edition web container. On the server side DWR uses a Servlet to interact with the Java objects and returns object representations of the Java objects or XML documents. DWR will be easy to get up and running and plays well with other Java technologies. If you are looking for a client-side and server-side framework that integrates well use DWR.
  • Google Web Toolkit (GWT) is client/server framework provided by Google that allows a developer to write an AJAX application in pure Java. The GWT takes care of the details of generating all the client-side code using a Java-to-JavaScript compiler. One of the key benefits of the GWT Software Developer Kit (SDK) is that it allows you to debug your applications in what is known as GWT hosted mode using an embedded browser (IE on Windows and Mozilla/Gecko on Linux) that is tied to the toolkit. In GWT hosted mode you setup through the code and debug it as it is running on both the client and server. The GWT contains a default set of widgets and widget containers. An application is built by coding a set of widgets and containers together much like would be done in a Swing application. The GWT Software Developer Kit (SDK) is limited to Linux and Windows XP/2000 though the web applications it generates are compatible with the latest generation of the mainstream browsers.
There are many new and emerging libraries for JavaScript and this list only reviews some of the more common libraries. When making a choice choose the library which suites your needs the best. While it might be better to choose one, there is nothing stopping you from using more than one framework. For a more extensive list of client-side frameworks see: Survey of AJAX/JavaScript Libraries.

Should I use XML or text, JavaScript, or HTML as a return type?

It depends. Clearly the 'X' in AJAX stands for XML, but several AJAX proponents are quick to point out that nothing in AJAX, per se, precludes using other types of payload, such as, JavaScript, HTML, or plain text.
  • XML - Web Services and AJAX seem made for one another. You can use client-side API's for downloading and parsing the XML content from RESTful Web Services. (However be mindful with some SOAP based Web Services architectures the payloads can get quite large and complex, and therefore may be inappropriate with AJAX techniqes.)
  • Plain Text - In this case server-generated text may be injected into a document or evaluated by client-side logic.
  • JavaScript - This is an extension to the plain text case with the exception that a server-side component passes a fragment of JavaScript including JavaScript object declarations. Using the JavaScript eval() function you can then create the objects on the client. JavaScript Object Notation (JSON), which is a JavaScript object based data exchange specification, relies on this technique.
  • HTML - Injecting server-generated HTML fragments directly into a document is generally a very effective AJAX technique. However, it can be complicated keeping the server-side component in sync with what is displayed on the client.
Mashup is a popular term for creating a completely new web application by combining the content from disparate Web Services and other online API's. A good example of a mashup is housingmaps.com which graphically combines housing want-ads from craiglist.org and maps from maps.google.com.

Are there Usability Issues with AJAX?

The nature of updating a page dynamically using data retrieved via AJAX interactions and DHTML may result in drastically changing the appearance and state of a page. A user might choose to use the browser's back or forward buttons, bookmark a page, copy the URL from the URL bar and share it with a friend via an email or chat client, or print a page at any given time. When designing an AJAX based application you need to consider what the expected behavior would be in the case of navigation, bookmarking, printing, and browser support as described below.
  • Navigation - What would be the expected behavior of the back, forward, refresh, and bookmark browser buttons in your application design. While you could implement history manipulation manually it may be easer to use a JavaScript frameworks such as Dojo that provides API's history manipulation and navigation control.
  • Bookmarking and URL sharing - Many users want to bookmark or cut and paste the URL from the browser bar. Dojo provides client-side for bookmarking and URL manipulation.
  • Printing - In some cases printing dynamically rendered pages can be problematic.
Other considerations as a developer when using AJAX are:
  • Browser Support - Not all AJAX/DHTML features are supported on all browsers or all versions of a browser. See quirksmode.org for a list of browser support and possible workarounds.
  • JavaScript disabled - You should also consider what happens if the user disables JavaScript. Additionally, there are several legitimate reasons why JavaScript and CSS support may be unavailable on a user's web browser.
  • Latency - Keep in mind latency in your design. A running application will be much more responsive than when it is deployed. Also keep in mind that when making multiple requests the return order is not guaranteed. For a more detailed discussion on latency see AJAX Latency problems: myth or reality?
  • Accessibility - Guaranteeing your site is accessible to people with disabilities is not only a noble goal, it is also requited by law in many markets. Some marvelous enabling technology is available to help people use the Web in spite of disabilities including visual, auditory, physical, speech, cognitive, and neurological disabilities. With a little forethought, and comprehension of some well documented best practices, you can assure that your application is compatible with that enabling technology.
Degradability is the term used to describe techniques used by web applications to adapt to the wide range of web browser capabilities. Many AJAX libraries have automatic degradability built in. But if you are coding your own custom AJAX functionality, simply taking some care to follow the best practices promoted by standards bodies like the World Wide Web Consortium (W3C), and grass root movements like the Web Standards community and many others, your application can run usefully on browsers that are incapable of AJAX behaviors. Granted, your application may loose some of the "wow factor" on these less capable browsers, but your application will still be usable.
Remember to not design with AJAX just for the sake of coolness. The reason you built your application is so people will use it. And people will not use your application if your application is not compatible with their web browser.

How do I debug JavaScript?

There are not that many tools out there that will support both client-side and server-side debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers.
  • Firefox/Mozilla/Netscape - Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers.
  • Safari - Has a debugger which needs to be enabled. See the Safari FAQ for details.
  • Internet Explorer - There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful.
While debuggers help a common technique knowing as "Alert Debugging" may be used. In this case you place "alert()" function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements.

Should I use an HTTP GET or POST for my AJAX calls?

AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for a consistent web application architecture.

How do I provide internationalized AJAX interactions?

Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following:
  • Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type:
·             
  
  • In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding see Comparing escape(), encodeURI(), and encodeURIComponent().
  • On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request.setCharactherEncoding("UTF-8");.
A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page.
    response.setContentType("text/xml;charset=;UTF-8");
    response.getWriter().write("invalid"); 
For more information on using AJAX with Java Enterprise Edition technologies see AJAX and Internationalization and for developing multi-lingual applications see Developing Multilingual Web Applications Using JavaServer Pages Technology.

How do I handle concurrent AJAX requests?

With JavaScript you can have more than one AJAX request processing at a single time. In order to insure the proper post processing of code it is recommended that you use JavaScript Closures. The example below shows an XMLHttpRequest object abstracted by a JavaScript object called AJAXInteraction. As arguments you pass in the URL to call and the function to call when the processing is done.
function AJAXInteraction(url, callback) {
 
    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
      if (req.readyState == 4) {
        if (req.status == 200) {
          if (callback) callback(req.responseXML);
        }
      }
    }
 
    this.doGet = function() {
      req.open("GET", url, true);
      req.send(null);
    }
    
    this.doPost = function(body) {
      req.open("POST", url, true);
      req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      req.send(body);
    }
}
 
function makeRequest() {
  var ai = new AJAXInteraction("processme", function() { alert("Doing Post Process");});
  ai.doGet();
}
 
The function makeRequest() in the example above creates an AJAXInteraction with a URL to of "processme" and an inline function that will show an alert dialog with the message "Doing Post Process". When ai.doGet() is called the AJAX interaction is initiated and when server-side component mapped to the URL "processme" returns a document which is passed to the callback function that was specified when the AJAXInteraction was created.
Using this closures insures that the proper callback function associated with a specific AJAX interaction is called. Caution should still be taken when creating multiple closure objects in that make XmlHttpRequests as to there is a limited number of sockets that are used to make requests at any given time. Because there are limited number of requests that can be made concurrently. Internet Explorer for example only allows for two concurrent AJAX requests at any given time. Other browsers may allow more but it is generally between three and five requests. You may choose to use pool of AJAXInteraction objects.
One thing to note when making multiple AJAX calls from the client is that the calls are not guaranteed to return in any given order. Having closures within the callback of a closure object can be used to ensure dependencies are processed correctly.
There is a discussion titled Ajaxian Fire and Forget Pattern that is helpful.

What do I do on the server to interact with an AJAX client?

The "Content-Type" header needs to be set to"text/xml". In servlets this may be done using the HttpServletResponse.setContentType()should be set to "text/xml" when the return type is XML. Many XMLHttpRequest implementations will result in an error if the "Content-Type" header is set The code below shows how to set the "Content-Type".
    response.setContentType("text/xml");
    response.getWriter().write("invalid"); 
You may also want to set whether or not to set the caches header for cases such as autocomplete where you may want to notify proxy servers/and browsers not to cache the results.
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("invalid"); 
Note to the developer: Internet Explorer will automatically use a cached result of any AJAX response from a HTTP GET if this header is not set which can make things difficult for a developer. During development mode you may want set this header.

Where do I store state with an AJAX client

As with other browser based web applications you have a few options which include:
  • On the client in cookies - The size is limited (generally around 4KB X 20 cookies per domain so a total of 80KB) and the content may not be secure unless encrypted which is difficult but not impossible using JavaScript.
  • On the client in the page - This can be done securely but can be problematic and difficult to work with. See my blog entry on Storing State on the Client for more details on this topic.
  • On the client file system - This can be done if the client grants access to the browser to write to the local file system. Depending on your uses cases this may be necessary but caution is advised.
  • On the Server - This is closer to the traditional model where the client view is of the state on the server. Keeping the data in sync can be a bit problematic and thus we have a solution Refreshing Data on this. As more information processing and control moves to the client where state is stored will need to be re-evaluated.

How do I submit a form or a part of a form without a page refresh?

When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false.
  
   
   
  
You can also submit data by associating a function with a form button in a similar way.
  
   
   
  
Note that the form "onSubmit" attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.
When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page.

Is the server or the client in control?

It depends. With AJAX the answer is more in between. Control can be more centralized in a server-side component or as a mix of client-side and server-side controllers.
  • Centralized server-side controller - When having a more centralized controller the key is to make sure the data in client-side page is in sync with that of the server. Some applications may keep all the state on the server and push all updates to client DOM via a simple JavaScript controller.
  • Client and server-side controllers - This architecture would use JavaScript to do all presentation related control, event processing, page manipulation, and rendering of model data on the client. The server-side would be responsible for things such as business logic and pushing updated model data to the client. In this case the server would not have intimate knowledge of the presentation short of the initial page that would be sent to the client page request. There are some use cases where an entire AJAX application can be written in a single page. Keep in mind if you choose this type of architecture that navigation and bookmarking should be considered.
Both methods are viable depending on what you are trying to accomplish. I tend to prefer spreading the control across the client and server.

Are there any security issues with AJAX?

JavaScript is in plain view to the user with by selecting view source of the page. JavaScript can not access the local filesystem without the user's permission. An AJAX interaction can only be made with the servers-side component from which the page was loaded. A proxy pattern could be used for AJAX interactions with external services.
You need to be careful not to expose your application model in such as way that your server-side components are at risk if a nefarious user to reverse engineer your application. As with any other web application, consider using HTTPS to secure the connection when confidential information is being exchanged.

When do I use a synchronous versus a asynchronous request?

Good question. They don't call it AJAX for nothing! A synchronous request would block in page event processing and I don't see many use cases where a synchronous request is preferable.

What about applets and plugins?

Don't be too quick to dump your plugin or applet based portions of your application. While AJAX and DHTML can do drag and drop and other advanced user interfaces there still limitations especially when it comes to browser support. Plugins and applets have been around for a while and have been able to make AJAX like requests for years. Applets provide a great set of UI components and APIs that provide developers literally anything.
Many people disregard applets or plugins because there is a startup time to initialize the plugin and there is no guarantee that the needed version of a plugin of JVM is installed. Plugins and applets may not be as capable of manipulating the page DOM. If you are in a uniform environment or can depend on a specific JVM or plugin version being available (such as in a corporate environment) a plugin or applet solution is great.
One thing to consider is a mix of AJAX and applets or plugins. Flickr uses a combination of AJAX interactions/DHTML for labeling pictures and user interaction and a plugin for manipulating photos and photo sets to provide a great user experience. If you design your server-side components well they can talk to both types of clients.

How do I handle the back and forward buttons?

While you could go out and create a custom solution that tracks the current state on your application I recommend you leave this to the experts. Dojo addresses the navigation in a browser neutral way as can be seen in the JavaScript example below.
function updateOnServer(oldId, oldValue, itemId, itemValue) {
    var bindArgs = {
        url:  "faces/ajax-dlabel-update",
        method: "post",
        content: {"component-id": itemId, "component-value": itemValue},
        mimetype: "text/xml",
                   load: function(type, data) {
               processUpdateResponse(data);
             },
        backButton: function() {
               alert("old itemid was " + oldId);
                                              },
        forwardButton: function(){
               alert("forward we must go!");
            }
     };
    dojo.io.bind(bindArgs);
}
The example above will update a value on the server using dojo.io.bind() with a function as a property that is responsible for dealing with the browser back button event. As a developer you are capable of restoring the value to the oldValue or taking any other action that you see fit. The underlying details of how the how the browser button event are detected are hidden from the developer by Dojo.
AJAX: How to Handle Bookmarks and Back Buttons details this problem and provides a JavaScript library Really Simple History framework (RSH) that focuses just on the back and forward issue.

How do I send an image using AJAX?

While it may appear that images are being sent when using AJAX with an application like Google Maps what is really happening is that the URLs of images are being send as the response of an AJAX request and those URLs are being set using DHTML.
In this example an XML document is returned from an AJAX interaction and the category bar is populated.
  1
  Books
  Fun to read
  books_icon.gif
 
  2
  Electronics
  Must have gadgets
  electronics.gif
 

Notice that the image-url element contains the location of the URL for the image representing a category. The callback method of an AJAX interaction will parse the response XML document and call the addCategory function for each category included in the response XML document. The addCategory function looks up a table row element "categoryTable" in body of the page and adds a row to the element which contains the image.
 
...
 
function addCategory(id, name, imageSrc) {
 
    var categoryTable = document.getElementById("categoryTable");
    var row = document.createElement("tr");
    var catCell = document.createElement("td");
    var img = document.createElement("img");
    img.src = ("images\\" + imageSrc);
    var link = document.createElement("a");
    link.className ="category";
    link.appendChild(document.createTextNode(name));
    link.setAttribute("onclick", "catalog?command=category&catid=" + id);
    catCell.appendChild(img);
    catCell.appendChild(link);
    row.appendChild(catCell);
    categoryTable.appendChild(row);
}

 
...
 
 
  
  
 

    
  
Body Here
Note that the source of the image is set to the image source. The image is loaded by a subsequent HTTP request for the image at the URL "images/books_icon.gif" or "images/electronic_icon.gif" that occurs when the img element is added to the categoryTable.

How do I create a thread to do AJAX polling?

JavaScript does not have threads. JavaScript functions are called when an event happens in a page such as the page is loaded, a mouse click, or a form element gains focus. You can create a timer using the setTimeout which takes a function name and time in milliseconds as arguments. You can then loop by calling the same function as can be seen in the JavaScript example below.
function checkForMessage() {
  // start AJAX interaction with processCallback as the callback function
}
 
// callback for the request
function processCallback() {
    
    // do post processing
    
    setTimeout("checkForMessage()", 10000);
}
Notice that the checkForMessage will continue to loop indefinitely. You may want to vary the increment the interval based on activity in the page or your use cases. You may also choose to have logic that would break out of the loop based on some AJAX response processing condition.

When should I use an Java applet instead of AJAX?

Applets provide a rich experience on the client side and there are many things they can do that an AJAX application cannot do, such as custom data streaming, graphic manipulation, threading, and advanced GUIs. While DHTML with the use of AJAX has been able to push the boundaries on what you can do on the client, there are some things that it just cannot do. The reason AJAX is so popular is that it only requires functionality built into the browser (namely DHTML and AJAX capabilities). The user does not need to download and/or configure plugins. It is easy to incrementally update functionality and know that that functionality will readily available, and there are not any complicated deployment issues. That said, AJAX-based functionality does need to take browser differences into consideration. This is why we recommend using a JavaScript library such as Dojo which abstracts browser differences. So the "bottom line" is: If you are creating advanced UIs where you need more advanced features on the client where you want UI accuracy down to the pixel, to do complex computations on the client, use specialized networking techniques, and where you know that the applet plugin is available for your target audience, applets are the way to go. AJAX/DHTML works well for applications where you know the users are using the latest generation of browsers, where DHTML/AJAX "good enough" for you, and where your developers have JavaScript/DHTML/AJAX skills. Many amazing things can be done with AJAX/DHTML but there are limitations. AJAX and applets can be used together in the same UIs with AJAX providing the basic structure and applets providing more advanced functionality. The Java can communicate to JavaScript using the Live-Connect APIs. The question should not be should framed as do I use AJAX or applets, but rather which technology makes the best sense for what you are doing. AJAX and applets do not have to be mutually exclusive.

How do I access data from other domains to create a mashup with Java?

From your JavaScript clients you can access data in other domains if the return data is provide in JSON format. In essence you can create a JavaScript client that runs operates using data from a different server. This technique is know as JSON with Padding or JSONP. There are questions as to whether this method is secure as you are retrieving data from outside your domain and allowing it to be excuted in the context of your domain. Not all data from third parties is accessible as JSON and in some cases you may want an extra level of protection. With Java you can provide a proxy to third party services using a web component such as a servlet. This proxy can manage the communication with a third party service and provide the data to your clients in a format of your choosing. You can also cache data at your proxy and reduce trips to service. For more on using a Java proxy to create mashups see The XmlHttpProxy Client for Java.

Does Java have support for Comet style server-side push?

Current AJAX applications use polling to communicate changes data between the server and client. Some applications, such as chat applications, stock tickers, or score boards require more immediate notifications of updates to the client. Comet is an event based low latency server side push for AJAX applications. Comet communication keeps one of the two connections available to the browser open to continously communicate events from the server to the client. A Java based solution for Comet is being developed for Glassfish on top of the Grizzly HTTP connector. See Enabling Grizzly by Jean-Francois Arcand for more details.

Comments

Popular posts from this blog

How to generate POJO's from Database for HBM or Annotated java beans?

This document will provide steps to reverse engineer POJO’s from Database tables for Hibernate mappings. Step 1 : Open Netbeans IDE and Create Project (Click to enlarge image) Step 2 : Create Hibernate configuration file Provide Database details with dialect Click finish button and it will generate ‘hibernate.cfg.xml’ files. Step 3 : Using Hibernate reverse engineering Wizard create ‘hibernate.reveng.xml’ file Click Next. Select Database tables to generate DAO’s. Click Finish button this will generate ‘hibernate.reveng.xml’ file Step 5 : Create POJO classes. Option One: For HBM mapping file Option Two: For Annotations Click finish button and it will generate POJO (DAO beans) into provided package. Ping me if you need any further help.

Chalata Hai???

I was reading article about logical Indian on Facebook. This very much discussed topic, punctuality of Indians for committed time. It is my experience that we Indian always take 5 to 10 mins liberty for committed appointment. This is part of “chalata hai” attitude. I wish we will able to get rid of such common habit. This also gets reflected in professional work. Software companies follows agile plan daily standup meeting. When senior member makes it mandatory to attend meeting then people somehow try’s (yes people literally tryJ) to come meeting and most of the time 2 to 5 mins late. Then question can we not able manage for 5/10 mins early than planned meeting. When working with other country people, I had experienced they make sure reach 5 to 10 mins before appointment. But we always give excuse about traffic but how come it happens every day and every meeting. It is “Chalata hai” attitude. Same attitude reflected when crossing red light, cutting lane, overtaking and b...