Offshore Outsourcing will help you to reduce cost and enhance your productivity

Home About Us Services Partners Articles Classifieds Directory Contact Us
   
Offshoring
Outsourcing
BPO
Computers Networks
Internet
Operating Systems
Data Storage
Telecommunications
Programming
Software Engineering
Information Technology
Online Rights - Law
Business
E-Commerce
IT Outsourcing
Business Consulting
Finance & Accounting
Graphic Design
Web Services
Search Engine Optimization
Open Source
Hardware
Security
Others
Games

AJAX A New Approach towords Web Applications

Working with web applications back in the bad old days, when making an application behave like a desktop app meant wrestling. Those were the days. Any thing now can said “exciting” its development of web application. At present all new modern and innovative projects are online on web.

Regardless of this, Web communication designers can’t help but feel a little jealous of our colleagues who create desktop software. Desktop applications have a prosperity and responsiveness that has seemed out of reach on the Web. Its ease that makes Web’s rapid, quick and fast.
 
Now with every single second this gap is closing. Have a look at Google’s Suggest or helping search bar. Have a look at Google’s Maps. Zoom in and Zoom out. Now users can use cursor to take the map and scroll around a bit. Mean to say is everything works instantly, with no pages reloading.

All these things like Google Maps, Google Suggest search bar, Gmail, Microsoft live search etc use a new way or a new approach to web applications that we at Adaptive Path have been calling Ajax. Ajax stands for Asynchronous JavaScript + XML, and it represents a fundamental shift in what’s possible on the Web.

What is Ajax?

You can’t call Ajax a new technology. It’s a merger of technologies, each booming in its own right, coming together in powerful new ways. Ajax incorporates:

  • Standards-based presentation using XHTML and CSS;
  • Lively show and interaction using DOM know as Document Object Model;
  • Data exchange and handling using XML and XSLT;
  • Asynchronous data recovery using XMLHttpRequest; Method
  • JavaScript binding the whole lot together.

 

A normal web application model works like: Most user actions in the interface generate an HTTP request back to the web server. Server does processing, retrieves the data, crunching numbers, talks to legacy systems and returns an HTML page to user. It’s a model adapted from the Web’s original use as a hypertext medium, but as fans of The Elements of User Experience know, what makes the Web good for hypertext doesn’t necessarily make it good for software applications. This approach makes a lot of technical sense, but it doesn’t make for a great user experience. While the server is doing its thing, what’s the user doing? That’s right, waiting. And at every step in a task, the user waits some more.

If we were designing the Web from scratch for applications, we wouldn’t make users wait around. Once an interface is loaded, why should the user interaction come to a halt every time the application needs something from the server? In fact, why should the user see the application go to the server at all?

Is Ajax Different?

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary an Ajax engine between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

Who’s Using Ajax

Google is playing its role in making Ajax a popular thing, its using Ajax every where in their applicaions. All of the major products Google has introduced over the last year like Orkut, Gmail, new Google Groups, Google Suggest, and Google Maps are Ajax based applications. Others are also following it.

At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is only going to grow. And because there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google’s lead in reaping the competitive advantage Ajax provides.

How to Make an HTTP Request

To make HTTP request to the server using JavaScript, you need an instance of a class that provides this functionality. In IE name of the class is XMLHTTP and In Mozilla, Safari and other browsers its called XMLHttpRequest

Sample code :

var httpReq;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpReq = new ActiveXObject("Microsoft.XMLHTTP");
}

Some versions of Mozilla browsers will not work properly if the response from the server doesn't have an XML mime-type header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not text/xml.

httpReq = new XMLHttpRequest();
httpReq.overrideMimeType('text/xml');

Next, you need to decide what you want to do after you receive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will do the work of processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function you plan to use, like this:

httpReq.onreadystatechange = nameOfTheFunction;

Remember there are no brackets after the function name and no parameters passed, because you're simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous function") and define the actions that will process the response right away, like this:

httpReq.onreadystatechange = function(){
    // do something
};

After you have declared as soon as you receive the response, you need to actually make the request. You need to call the open() and send() methods of the HTTP request class, like this:

httpReq.open('GET', 'http://www.example.org/some.file', true);
httpReq.send(null);
  • The first parameter of the call to open() is the HTTP request method GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request.
  • The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a 'permission denied' error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.
  • The third parameter sets whether the request is asynchronous. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.

The parameter to the send() method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:

name=value&anothername=othervalue&so=on

Note that if you want to POST data, you have to change the MIME type of the request using the following line:

httpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Otherwise, the server will discard the POSTed data.

Handling the Server Response

httpReq.onreadystatechange = nameOfTheFunction;

First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it's OK for you to continue processing it.

if (httpReq.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}

The full list of the readyState values is as follows:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)

The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the W3C site. For our purposes we are only interested in 200 OK response.

if (httpReq.status == 200) {
    // perfect!
} else {
    // there was a problem with the request,
    // for example the response may be a 404 (Not Found)
    // or 500 (Internal Server Error) response codes
}

After you've checked the state of the request and the HTTP status code of the response, it's up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:

  • httpReq.responseText will return the server response as a string of text
  • httpReq.responseXML will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Simple Ajax Example

In this example our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." and then we'll alert() the contents of the test.html file. For this purpose you need to make test.html file and write "I'm a test" in it.

<script type="text/javascript" language="javascript">
function makeRequest(url){
	var httpReq;
	if (window.XMLHttpRequest){
		// Mozilla, Safari etc
		httpReq = new XMLHttpRequest();
		if (httpReq.overrideMimeType){
			httpReq.overrideMimeType('text/xml');
			// See note below about this line
		}
	}
	else if (window.ActiveXObject) {
		// IE
		try{
		  httpReq = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try{
			  httpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	if (!httpReq) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
		httpReq.onreadystatechange = function(){
			alertContents(httpReq); 
		};
        httpReq.open('GET', url, true);
        httpReq.send(null);
    }
	function alertContents(httpReq) {
		if (httpReq.readyState == 4) {
			if (httpReq.status == 200) {
				alert(httpReq.responseText);
			} else {
				alert('There was a problem with the request.');
            }
        }
    }
</script>
<span
    style="cursor: pointer; text-decoration: underline"

    onclick="makeRequest('test.html')">
        Make a request
</span>


Working of the example:

  • The user clicks the link "Make a request" in the browser;
  • This calls the makeRequest() function with a parameter the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

Note: The line httpReq.overrideMimeType('text/xml'); above will cause JavaScript Console errors in Firefox 1.5 or later, as documented in bug 311724 if the page retrieve by XMLHttpRequest is not valid XML (e.g., if it is plain text). This is actually correct behavior; this article will be revised soon to address this change.

Note 2: if you are sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. If you do not set header Content-Type: application/xml, IE will throw a JavaScript error, 'Object Expected', after the line where you try to access an XML element. If you do not set header Cache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging "challenging."

Note 3: if the httpReq variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition. Declaring the httpReq variable local to the function and passing it to the alertContent() function prevents the race condition.

Note 4: To register the callback function onreadystatechange, you cannot have any arguments. That's why the following code does not work:

httpReq.onreadystatechange = alertContents(httpReq);
// (does not work)

So, to register the function successfully, you can either pass the arguments indirectly via the anonymous function or use httpReq as a global variable. Examples follow:

httpReq.onreadystatechange = function() {
	alertContents(httpReq); 
};
//1 (simultaneous request)
httpReq.onreadystatechange = alertContents;
//2 (global variable)

Method 1 lets you have several requests processed simultaneously, while method 2 is used if httpReq is a global variable.


Note 5: In the event of a communication error (such as the webserver going down), an exception will be thrown in the onreadystatechange method when attempting to access the .status variable. Make sure that you wrap your if...then statement in a try...catch. (See: https://bugzilla.mozilla.org/show_bug.cgi?id=238559).

function alertContents(httpReq) {

        try {
            if (httpReq.readyState == 4) {
                if (httpReq.status == 200) {
                    alert(httpReq.responseText);
                } else {
                    alert('There was a problem with the request.');
                }
            }
        }
        catch( e ) {
            alert('Caught Exception: ' + e.description);
        }

    }

Working with the XML Response

In the previous example, after the response to the HTTP request was received we used the responseText property of the request object, which contained the contents of the test.html file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:

<?xml version="1.0" ?>
<root>
    I'm a test.
</root>

In the script we only need to change the request line to:

...
onclick="makeRequest('test.xml')">
...

Then in alertContents(), we need to replace the line alert(httpReq.responseText); with:

var xmldoc = httpReq.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

For more: Mozilla's DOM implementation documents.