Sunday, September 09, 2007

XMLHttpRequest - basics you should know ...

You have heard of it a number of times, haven't you ?

Here are few basic things you need to get you started

What is XMLHttpRequest ?

A Javascript object which can be used to retrieve data via HTTP

So, you can retrieve XML data ?

Not really, any type of data, not just XML

What's the dope ?

You can retrieve data from a server without having to refresh the page, this differs from the traditional page where you if you had to retrieve data - you had to do send the data to the server and retrieve it through a different page

Give me an example now!

var request = new XMLHttpRequest();
request.open('GET', 'http://techflock.blogspot.com', false);
request.send(null);
if(request.status == 200)
dump(request.responseText);
What happens to the browser when data is being retrieved ? Does it hang ?

You can prevent action when you are performing your operation. However if you want the user to still use the application when you are performing an operation, you could request the data asynchronously

Asynchronously ?

var request = new XMLHttpRequest();
request.open('GET', 'http://techflock.blogspot.com/', true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
if(request.status == 200)
dump(request.responseText);
else
dump("Error loading page\n");
}
};
req.send(null);

the onreadystatechange property will have a function callback assigned which will handle the response of your action

Works on both Mozilla and IE based browsers ?

Yes, but differently - For Mozilla based browsers, the above works

For IE, you have to

var request = new ActiveXObject("MSXML2.XMLHTTP.3.0");

Great! Where can I find more ?

Mozilla Developer Site

Apple

Microsoft MSDN


Examples ?

Here

1 comment:

Orderbringer said...

Your post was helpful, thanks for getting me started on this topic. :-)