Site Navigation
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.
function ajax_new() {
var req;
if(window.XMLHttpRequest)
req = new XMLHttpRequest();
else {
if(window.ActiveXObject)
req = new ActiveXObject('Msxml2.XMLHTTP');
else
req = new ActiveXObject('Microsoft.XMLHTTP');
}
return req;
}
In order to initialize a new XMLHttpRequest object we can now simply do
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.
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.
var ajax = ajax_new();
ajax.open('GET', 'ourtextfile.txt', true);
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.
ajax.onreadystatechange = function() {
if(ajax.readyState == 4) {
if(ajax.status == 200) {
alert(ajax.responseText);
} else
alert('Server returned Error:' + ajax.status);
}
}
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.
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
Comments to this post: (2)
RSS Feed for comments
rob
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
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