Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

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) {
handler(request.responseText);
}
else
alert("Problem recieving data:" + request.statusText);
}
}
if (method == "GET") {
request.open("GET", url + "?" + data, true);
request.send(null);
}
else if (method == "POST") {
request.open("POST", url, true);
request.setRequestHeader("Content-length", data.length);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.send(data);
}
}
}
}

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) {
document.write(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.

Thursday, May 21, 2009

It's odd working with IE - Part 2. comma

2. comma makes big difference in IE.
Like most technical people out there, I used to be chased by time. So, it happened from time to time to insert unwanted character by hitting keyboard without notice when I hastily moving around numerous codes. However, IE stop all my script, once, I mistakenly put comma ‘,’ in the declaration of Javascript object as follow;

<script type=”text/javascript”>
var test = {
abc: new Array(),

def: function(arg1, arg2) {

},
ghl: function(arg3) {

},
}

</script>

Because I prefer use Aptana when editing HTML pages, I did not notice what’s happened. (By the way Aptana does not provide strict error checking when it comes to Javascript) Furthermore, because I usually develop using Firefox under Linux environment, even in the first running test it goes without noticed. (Firefox seemed generous to people like me.) However, when I loaded in IE6 (I only installed IE version 6 in Linux) using sometime later, I was surprised to see that not a single line of Javascript was running from the web page, and no error message was shown.

It is true that I still did not find an editor with perfect syntax or semantic checking, in the market. Furthermore, unfortunately, Unlike C++ or Java, it does not comes with error checking program such as compiler. So, it comfortable to check such error.

There are, however, ways to avoid this pitfall.

a. Using JSLint: just as link does for C program, JSLint can hint erroneous or even under-performing code. Online version can be accessed using http://www.jslint.com/, plug-in version can be found in http://www.rockstarapps.com.
b. Using multiple editor: Just to double check errors that may remain in source code, reviewing code with another editor(editor comes with ATF, Ajax Toolkit Framework, for example) with more rigorous error checking is also helpful.

P.S. By the way, because I’m a heavy user of Eclipse, editor or plug-in is viewed from Eclipse environment.