Sunday, May 24, 2009

Simple object is enough for simple Ajax

In modern web environment, Asynchronous Javascript And XML, a.k.a. Ajax, is common technique or technology to make web more dynamic. There are many Ajax frameworks in the open source community such as GWT from Google, Django, Dojo, and many more. However, in the bottom of every Ajax framework, there is single Javascript object called XMLHttpRequest. It is this browser object that make these bulky frameworks request data to sever, asynchronously.

So, if simple text-based communication or simple XML document that does not need heavy framework to manipulate every inches of documents is required, you may not need to embed bulky framework in your web program. You may only need to know how to use XMLHttpRequest.

The following is one of the example to show how to use XMLHttpRequest. It is simple constructor function that you can reuse when you need Ajax. Because of the length of the article, I’ll introduce client side first.

function AjaxClient(){
this.getXmlHttpRequest = function(){
if (window.XMLHttpRequest)
return new XMLHttpRequest();
try {
return new ActiveXObject("Microsoft.XMLHTTP");
catch (e) {
alert("The browser is not supported!");
return null;
this.sendRequest = function(url, method, data, handler){
var request = this.getXmlHttpRequest();
if (request != null) {
request.onreadystatechange = function onStateChange(){
if (request.readyState == 4) {
if (request.status == 200) {
alert("Problem recieving data:" + request.statusText);
if (method == "GET") {"GET", url + "?" + data, true);
else if (method == "POST") {"POST", url, true);
request.setRequestHeader("Content-length", data.length);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");

The first method in AjaxClient is GetXmlHttpRequest() to create XMLHttpRequest. Before version 7, Internet explorer need ActiveX component to create XMLHttpRequest object. I believe that many people still use Internet explorer 6 or even 5, and that it may still need to discriminate older version of IE's from other browsers.

Before going further, let’s look at the XmlHttpRequest.

interface XMLHttpRequest {
// event handler
attribute EventListener onreadystatechange;

// state
const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
readonly attribute unsigned short readyState;

// request
void open(in DOMString method, in DOMString url);
void open(in DOMString method, in DOMString url, in boolean async);
void open(in DOMString method, in DOMString url, in boolean async, in DOMString user);
void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password);
void setRequestHeader(in DOMString header, in DOMString value);
void send();
void send(in DOMString data);
void send(in Document data);
void abort();

// response
DOMString getAllResponseHeaders();
DOMString getResponseHeader(in DOMString header);
readonly attribute DOMString responseText;
readonly attribute Document responseXML;
readonly attribute unsigned short status;
readonly attribute DOMString statusText;

from “The XMLHttpRequest Object

As can be seen from definition, XMLHttpRequest has three methods, open(), send() and abort() in request side, two methods in response side, one event handler, and five read-only attributes including readyState. open() accept at least two arguments. The first argument method is one among “GET”, “POST”, “HEAD”, “PUT”, “DELETE”, “OPTIONS.” The second argument is URL of server. If you use less than 255 bytes(which I believe is almost the least length of GET URL that an old browser can permit) of data and server URL, you can use “GET” and embed necessary data in URL as key and value pairs. If you want to send more than 255 bytes of data, you use “POST” and embed data into the body of HTTP protocol through send(). More details can be found in W3C documents.

Back to my example, sendRequest() accepts URL of server, method of request which is either “GET” or “POST”, parameters to send, and handler which is your code to run after data is received from server.

Because handler will be wrapped by already prepared code, which monitors readyState to be “4 (DONE)” and status be “200 (OK),” your handler focus on what to do with data received. As in the sample below.

function myHandler(receivedData) {

The usage is simple. After include AjaxClient in your script, you create AjaxClient() object, and invoke sendRequest() like this.

client = New AjaxClient();
client.sendRequest(“http://localhost:8080/test”, “POST”, “Give me something”, myHandler);

Once call is successfully finished, you can see what server has sent in the browser.

No comments:

Post a Comment