December 29, 2008

XMLHttpRequest and XUL

"XMLHttpRequest has become the spearhead of the new web revolution.

In this article we will explore and understand the simplicity of its use.
The only AJAX method you will ever need

function WebMethod(url,request,callback)
{
var http = new XMLHttpRequest();
var mode = request?"POST":"GET";
http.open(mode,url,true);
if(mode=="POST"){http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
http.onreadystatechange=function(){if(http.readyState==4){callback(http.responseText);}};
http.send(request);
}

Cross-browser instantiation

For the purposes of learning XUL in Mozilla browsers, our direct approach will suffice.
But if you need to make your applications cross-browser compatible, then use the following code to get the XMLHttpRequest object.

function getXmlHttpObject(){
var http=false;
try {http=new XMLHttpRequest();} catch (e1){
try {http=new ActiveXObject("Msxml2.xmlhttp");} catch (e2){
try {http=new ActiveXObject("Microsoft.xmlhttp");} catch (e3){http=false;}}}
return http;
}

Asynchronous calls

It is absolutely imperative that we use asynchronous calls in our server trips, internet latency makes synchronous calls an ugly alternative we should avoid at all cost.

http.open(mode,url,true); // Asynchronous
or
http.open(mode,url,false); // Synchronous

In a synchronous way, we open the connection, we send the request and wait for the response in the same line, locking the browser from any user interaction until the response arrives.


http.open(mode,url,false); // Synchronous request
http.send(request); // Locked until response returns
alert(http.responseText); // Then next line executes

Two-Step Dance

Asynchronous calls can only be achieved in a two step process: send the request and forget about it, the callback function will receive the response whenever it is ready.

Here is where our beautifully crafted WebMethod function comes handy:

function LoadMail(){
// ShowMail is the callback function that will receive the response
WebMethod("example.com/getmail.php","folder=inbox",ShowMail);
}
function ShowMail(response){
// do stuff with response
alert(response);
}

It may be a little difficult at the beginning to understand the concept of two step asynchrony
But as long as you split your process in two parts, and use the WebMethod call, things will become easier for you.
Get or Post

The most used http modes are GET and POST and we made it easier for you to make the appropriate request.
Pass the parameters in the url as a query string and it wil be sent as GET
Pass the parameters as the request argument and it will be sent as a POST

// GET mode, parameters in url
WebMethod("example.com/getmail.php?folder=inbox",null,ShowMail);

// POST mode, parameters as request
WebMethod("example.com/getmail.php","folder=inbox",ShowMail);
" georgenava.googlepages.com

No comments:

Post a Comment