vegUI.org home of the javascript based window manager and AJAX framework
 
Comment has been reported, thanks for helping to improve the quality of this website

AJAX Series: Tutorial #1 - Sending a simple request

written by vegu on 29 Jan, 2007 12:55:44
I like to write my tutorials in a way that on the code side of things a lot will be explained via comments embedded in the code examples. As this should be more readable by the user and keeps my writing flow going in fluid way :).

It is probably a redundant thing for me to explain what AJAX does and how to crate the XMLHttpRequest object, as there are a million tutorials out there already that tell you how to do that. I will still do so for completeness sake though, but i will try to keep it short.


AJAX, the new flashy word that pops up everywhere when people are talking about web development and web 2.0.

It stands for Asynchronous Javascript and XML and basically allows you to utilize the XMLHttpRequest object to send requests to the server and handle the server response without having to reload the page and without affecting the current process flow of the script.

It happens in the "background" so to say or asynchronous to the script execution.

There are many AJAX frameworks out there, some simple some complex, but we will take a look at the core of ajax based development and start from scratch.

This tutorial is the first installment of the AJAX tutorial series on vegui.org and will show you how to send a simple request using the XMLHttpRequest object provided by the browser, so let's get going.

In order to be able to do some AJAX magic we need to first create an instance of the XMLHttpRequest object. This object will be used by us to send requests to our webserver and also to deal with the response we get back.

So lets start with that, we will build a function that creates our XMLHttpRequest object with cross browser support.

code: js
function ajax_new() {
var req;

/* This works in mozilla based browsers
* opera, and IE 7. It probably also works for less
* popular browser although i have never tested
* it
*/


if(window.XMLHttpRequest)
req = new XMLHttpRequest();

/* for IE < 7 we need to be a bit more tricky */

else {
if(window.ActiveXObject)
req = new ActiveXObject('Msxml2.XMLHTTP');
else
req = new ActiveXObject('Microsoft.XMLHTTP');
}

/* if req is null it will also be returned as null, telling
* us that there was a problem when trying to create
* the XMLHttpRequest object. If everything worked out fine
* the new XMLHttpRequest object is returned
*/


return req;

}

In order to initialize a new XMLHttpRequest object we can now simply do

code: js
var ajax = ajax_new();

and it will work in all popular browsers, and most likely the less popular ones as well.

You can also do some error handling, simply check if the value returned by the function was null or not.

code: js
if( !(ajax = ajax_new()) )
alert('Could not create XMLHttpRequest object');

Alright, now that we can create our XMLHTTPRequest object let's move away for a second and look on the server side of things.

In order to do our little test we will create a simple text file that we will later request ajax style.

The content of the text file can be any random text such as


"Hello world!"


Tacky, isn't it?

That is as simple as it gets, okay back to ajax.

In order to request our text file using ajax we need to use the open and send method of our XMLHttpRequest object. The open call opens the connection to the web server and the send method sends the request.

For starters we will do a simple GET request, which means we won't need to send anything at all. The send call is still required though, but we will send null.

code: js

/* creating a new XMLHttpRequest object */

var ajax = ajax_new();

/* open the connection for a GET request, and yes it is case sensitive
* it is assumed that the text file you created is located in the same
* location as the web page executing this script
*
* If it is not adjust the relative path to point to the text file
*
* The third argument is true and specifies that the request will be
* async to the execution of the script. If you set it to false
* the request will be synchronus and delay further execution of the
* script until it is done.
*/


ajax.open('GET', 'ourtextfile.txt', true);

/* since it's a GET request we dont want to send anything */

ajax.send(null);

Sweet, but when executed it does not seem to do anything. Well it does something, currently hidden from our eyes, namely sending the request to the server. If you have access to your web server's access logs you will see that the text file was requested.

So lets deal with the response we get from the server.

In order to do so we need to utilize the onreadystatechange event of the XMLHttpRequest object. This event fires every time the object's ready state changes.

code: js
ajax.onreadystatechange = function() {

/* we check the readyState, thanks to closure the ajax variable
* will also point to our XMLHttpRequest object in the variable
* scope of the function
*
* The ready states are:
*
* 0 - Initialized
* 1 - Opened (on open() call)
* 2 - Sent (after send())
* 3 - Receiving (while receiving response from the server)
* 4 - Loaded (when done)
*
* We're only interested in readystate 4 when the server response
* has been fully received
*/


if(ajax.readyState == 4) {

/* now we need to check the status property, it holds the status type
* returned by the server. ie. 200 on success, 404 on not found , 403
* on access denied and so forth.
*/


if(ajax.status == 200) {

/* the responseText property holds the raw content received from the
* server. In our case the little line we put into our text file
*/


alert(ajax.responseText);

} else
alert('Server returned Error:' + ajax.status);

}
}

/* IMPORANT the onreadystatechange event needs to be set before we
* send the request
*/


ajax.open('GET', 'ourtextfile.txt', true);
ajax.send(null);

If you load the page now there should be an alert message holding the "hello world!" text or whatever text you put into your text-file almost instantly.

Using absolute URLs


First off, you cannot use XMLHttpRequest to access files that are on other webservers as that is prohibited for security reasons by the browser. However it is possible to request absolute URLs as long as they point to the same server the ajax script is executed on.

code: js
ajax.open('GET', 'http://www.vegui.org', true);

Note that the address needs to be identical with the address you used to request the script in the first place.

So if you accessed your ajax script over http://www.yoururl.com/sweet_ajax_script.html and want to request a file over the url http://yoururl.com/sometextfile.txt it wont work (note: the missing www), because the www sub-domain does not necessirly point to the same IP address as the root resource record (yoururl.com).

In the next tutorial we will take a look at sending data with our request using the POST method.

Related Posts


Your Comment

name:*
email-address:

Are you human?



Comments to this post: (2)

RSS Feed for comments RSS Feed for comments
rob
on 06 Dec, 2007 - 20:19:45

I tried this routine exactly, it works fine on IE but hangs in the event handler on FireFox- what is the problem?

Report this comment
vegu
on 07 Dec, 2007 - 14:51:45

Strange, i tested it in firefox, and it's working here. Hard to say whats wrong without seeing the code, if you want you can email it to vegu@vegui.org and i will take a look :)

Report this comment