Search This Blog

Wednesday, January 20, 2010

AJAX

What is Ajax?
Asynchronous JavaScript and XML or Ajax for short is new web development technique used for the development of most interactive website. Ajax helps you in making your web application more interactive by retrieving small amount of data from web server and then showing it on your application. You can do all these things without refreshing your page.
Usually in all the web applications, the user enters the data into the form and then clicks on the submit button to submit the request to the server. Server processes the request and returns the view in new page ( by reloading the whole page). This process is inefficient, time consuming, and a little frustrating for you user if the only the small amount of data exchange is required. For example in an user registration form, this can be frustrating thing for the user, as whole page is reloaded only to check the availability of the user name. Ajax will help in making your application more interactive. With the help of Ajax you can tune your application to check the availability of the user name without refreshing the whole page.
Understanding the technology behind Ajax
Ajax is not a single technology, but it is a combination of many technologies. These technologies are supported by modern web browsers. Following are techniques used in the Ajax applications.
• JavaScript:
JavaScript is used to make a request to the web server. Once the response is returned by the webserver, more JavaScript can be used to update the current page. DHTML and CSS is used to show the output to the user. JavaScript is used very heavily to provide teh dynamic behavior to the application.

• Asynchronous Call to the Server:
Most of the Ajax application used the XMLHttpRequest object to send the request to the web server. These calls are Asynchronous and there is no need to wait for the response to come back. User can do the normal work without any problem.

• XML:
XML may be used to receive the data returned from the web server. JavaScript can be used to process the XML data returned from the web server easily.
How Ajax Works?
When user first visits the page, the Ajax engine is initialized and loaded. From that point of time user interacts with Ajax engine to interact with the web server. The Ajax engine operates asynchronously while sending the request to the server and receiving the response from server. Ajax life cycle within the web browser can be divided into following stages:
• User Visit to the page: User visits the URL by typing URL in browser or clicking a link from some other page.

• Initialization of Ajax engine:
When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can also be set to continuously refresh the page content without refreshing the whole page.

• Event Processing Loop:
* Browser event may instruct the Ajax engine to send request to server and receive the response data
* Server response - Ajax engine receives the response from the server. Then it calls the JavaScript call back functions
* Browser (View) update - JavaScript request call back functions is used to update the browser. DHTML and css is used to update the browser display.
Benefits of Ajax
Ajax is new very promising technology, which has become extremely popular these days. Here are the benefits of using Ajax:
• Ajax can be used for creating rich, web-based applications that look and works like a desktop application

• Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like XML, CSS, DHTML. etc. So, its very easy to learn Ajax

• Ajax can be used to develop web applications that can update the page data continuously without refreshing the whole page
As the use of XML and web services is increasing day by day, it is good to connect an HTML page with XML, with the help of that we can get interim updates so easily without reloading the page. It is possible due to the XMLHttpRequest object, which is responsible for retrieving and submitting the XML data directly from the client side. It relies on Document Object Model (DOM) to convert the retrieved XML data into HTML.
Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX object. Afterward Mozilla and Apple's Safari also implemented in their own style.
XMLHttpRequest object facilitates the web developer a lot because with the help of this object you can update the page with new data without reloading the page, communicate with server in the background, request and receive data from the web server.
Creating an XMLHttpRequest object.
We can create an instance of the XMLHttpRequest in most of the modern popular browsers, and in the old versions of the browsers we need to create an object of ActiveXObject.
var xmlobj=new XMLHttpRequest ();
var activeobj=new ActiveXObject("Microsoft.XMLHTTP");
How to use an XMLHttpRequest Object and Handle the server response:
We need to create an XMLHttpRequest, after that we will use few important functions like:
1. onreadystatechange property: After submitting the request to the server, we need to store the response from the server. onreadystatechange property stores the response from the function which process the server.
2. readystate property: readystate property holds the state of the server response, every time readystate property change , onreadystatechange function executes. Possible values and their meaning are given below:
State The Request is:
0 Not initialized
1 Has been set up
2 Has been sent
3 In process
4 Is complete
3. responseText property: The data sent back from the server is stored and retrieved later with the help of responseText property.

AJAX XMLHttpRequest
« Previous
Next Chapter »

________________________________________
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).
AJAX Browser Support
« Previous
Next Chapter »

________________________________________
The keystone of AJAX is the XMLHttpRequest object
________________________________________
The XMLHttpRequest
All new browsers support a new built-in JavaScript XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).
This object can be used to request information (data) from a server.
Let's update our HTML file with a JavaScript in the section:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
}
Example explained
Try to create a XMLHttpRequest object:
xmlhttp=new XMLHttpRequest()
If not (if IE5 or IE6) create an ActiveXObject:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
Open the request object:
xmlhttp.open("GET",url,false)
Send your request to your server:
xmlhttp.send(null)
Update your page with the response from the server:
document.getElementById('test').innerHTML=xmlhttp.responseText
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.
In the next chapter you will learn more about the XMLHttpRequest.
________________________________________
All Together Now








Click to let AJAX change this text








AJAX - The XMLHttpRequest Object
« Previous
Next Chapter »

________________________________________
Important Methods and Properties of the XMLHttpRequest object.
________________________________________
Important Methods
The XMLHttpRequest object has 2 important methods:
 The open() method
 The send() method
________________________________________
Sending an AJAX Request to a Server
To send a request to a web server, we use the open() and send() methods.
The open() method takes three arguments. The first argument defines which method to use (GET or POST). The second argument specifies the name of the server resource (URL). The third argument specifies if the request should be handled asynchronously.
The send() method sends the request off to the server. If we assume that requested a file called "time.asp", the code would be:
url="time.asp"
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
In the example we assume that the current web page and the requested resource are both in the same file directory.
________________________________________
Important Properties
The XMLHttpRequest object has 3 important properties:
 The responseText property
 The readyState property
 The onreadystatechange property
________________________________________
The responseText property
The XMLHttpRequest object stores any data retrieved from a server as a result of a server request in its responseText property.
In the previous chapter we copied the content of the responsText property into our HTML with the following statement:
document.getElementById('test').innerHTML=xmlhttp.responseText

________________________________________
XMLHttpRequest Open - Using False
In the examples (from the previous pages) we used this simplified syntax:
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
The third parameter in the open call is "false". This tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed.
For small applications and simple server request, this might be OK. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.
________________________________________
XMLHttpRequest Open - Using True
By changing the third parameter in the open call to "true", you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent.
Because you cannot simply start using the response from the server request before you are sure the request has been completed, you need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion.
In this onreadystatechange function you must test the readyState property before you can use the result of the server call.
Simply change the code to:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);

________________________________________
The readyState property
The readyState property holds the status of the server's response.
Possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

________________________________________
The onreadystatechange property
The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readyState property changes.
You can store a full function in the property like this:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
Or you can store the name of a function like this:
xmlhttp.onreadystatechange=state_Change()
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
...
...
...
function state_Change()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}

Asynchronous JavaScript Technology and XML (Ajax) With the Java Platform






Print-friendly Version


By Greg Murray, June 9, 2005; updated October 2006




Anyone who has used Flickr, GMail, Google Suggest, or Google Maps will realize that a new breed of dynamic web applications is emerging. These applications look and act very similar to traditional desktop applications without relying on plug-ins or browser-specific features. Web applications have traditionally been a set of HTML pages that must be reloaded to change any portion of the content. Technologies such as JavaScript programming language and cascading style sheets (CSS) have matured to the point where they can be used effectively to create very dynamic web applications that will work on all of the major browsers. This article will detail several techniques that you can use today to enable your web applications to be more rich and interactive like desktop applications.


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.


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.
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("valid");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
}
}
}


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.

valid



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.






The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as or