Académique Documents
Professionnel Documents
Culture Documents
Ajax isn�t a technology. It�s really several technologies, each flourishing in its
own right, coming together in powerful new ways. Ajax incorporates:
If you require support for browsers that are older than these, methods using
iframes provide a viable solution; however, coding for these browsers will also
limit your ability to utilize standard JavaScript DOM methods. This article will
focus on the more contemporary XMLHttpRequest method.
Creating an XMLHttpRequest Object
For any browser, except Internet Explorer, we can create an XMLHttpRequest object
like this:
Note: this also means that if users have ActiveX objects disabled in Internet
Explorer, they will be unable to use XMLHttpRequest even if JavaScript is enabled.
To cope with the differences in object creation syntax used by these browsers,
it's best to use a try/catch structure to automatically provide you with the
correct object, or return an error if the XMLHttpRequest object is not available:
try
{
var requester = new XMLHttpRequest();
}
catch (error)
{
try
{
var requester = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (error)
{
return false;
}
}
Thankfully, the difference between implementations ends there, and all subsequent
method calls to the XMLHttpRequest object can be performed irrespective of which
browser the script's running in.
Transporting Data using an XMLHttpRequest Object
Once an XMLHttpRequest object has been created, we must call two separate methods
in order to get it to retrieve data from a server.
open() initialises the connection we wish to make, and takes two arguments, with
several optionals. The first argument is the type of request we want to send; the
second argument identifies the location from which we wish to request data. For
instance, if we wanted to use a GET request to access feed.xml at the root of our
server, we'd initialise the XMLHttpRequest object like this:
requester.open("GET", "/feed.xml");
The URL can be either relative or absolute, but due to cross-domain security
concerns, the target must reside on the same domain as the page that requests it.
The open() method also takes an optional third boolean argument that specifies
whether the request is made asynchronously (true, the default) or synchronously
(false). With a synchronous request, the browser will freeze, disallowing any user
interaction, until the object has completed. An asynchronous request occurs in the
background, allowing other scripts to run and letting the user continue to access
their browser. It's recommended that you use asynchronous requests; otherwise, we
run the risk of a user's browser locking up while they wait for a request that
went awry. open()'s optional fourth and fifth arguments are a username and
password for authentication when accessing a password-protected URL.
Once open() has been used to initialise a connection, the send() method activates
the connection and makes the request. send() takes one argument, allowing us to
send extra data, such as CGI variables, along with the call. Internet Explorer
treats it as optional, but Mozilla will return an error if no value is passed, so
it's safest to call it using:
requester.send(null);
To send CGI variables using the GET request method, we have to hardcode the
variables into the open() URL:
requester.open("GET", "/query.do?name=Bob&email=bob@example.com");
requester.send(null);
To send CGI variables using the POST request method, the CGI variables can be
passed to the send() method like so:
requester.open("POST", "/query.do");
requester.send("name=Bob&email=bob@example.com");
Once we've called send(), XMLHttpRequest will contact the server and retrieve the
data we requested; however, this process takes an indeterminate amount of time. In
order to find out when the object has finished retrieving data, we must use an
event listener. In the case of an XMLHttpRequest object, we need to listen for
changes in its readyState variable. This variable specifies the status of the
object's connection, and can be any of the following:
0 - uninitialized - Object is not initialized with data.
3 - interactive - User can interact with the object even though it is not fully
loaded.
requester.onreadystatechange = stateHandler;
SITEPOINT BOOKS
"The JavaScript Anthology: 101 Essential Tips, Tricks & Hacks"
Photo of Cameron and James
by James Edwards & Cameron Adams
Follow two of the world�s most innovative JavaScript virtuosos as they walk you
through over 100 modern, best practice, JavaScript solutions.
This book will change the way you use JavaScript.
function stateHandler()
{
if (requester.readyState == 4)
{
if (requester.status == 200)
{
success();
}
else
{
failure();
}
}
return true;
}
Even though the XMLHttpRequest object allows us to call the open() method multiple
times, each object can really only be used for one call, as the onreadystatechange
event doesn't update again once readyState changes to "4" (in Mozilla). Therefore,
we have to create a new XMLHttpRequest object every time we want to make a remote
call.
Parsing the Data in an XMLHttpRequest Object
Depending upon the complexity of the data, it may be easier to return data simply
as a plain text string, thereby making the XML in XMLHttpRequest redundant.
However, for more complex data types, you'll probably want to use an XML format,
such as this:
We are able to access different parts of the data using standard DOM access
methods. Remember that data contained between tags is considered to represent
child text nodes of the parent, so we have to take that extra layer of structure
into account when we retrieve the data:
We must also be careful about whitespace: indenting values in the XML file may
produce unwanted whitespace in the value, or add additional text nodes.
Once we've parsed the data from the XMLHttpRequest object, we're free to change,
delete and write it onto our Web page as we see fit!