Using the XML HTTP Request Object
This article was originally written in April 2002, I've decided to fix and update it as the objects finally seem to be getting some popularity. The 2002 version is still available. This version December 2004, there's also a September 2004 version.
Internet Explorer on Windows, Konqueror, Safari on Mac OS-X and Mozilla on all platforms provide a method for client side javascript to make HTTP requests, Opera 7.6preview 1 also now features the object. This allows you to make HEAD requests to see when a resource was last modified, or to see if it even exists. It makes your scripting options more flexible allowing for POST requests without having the page change, and opens up the possibility of using PUT, DELETE etc. These methods are increasingly used to provide Richer Web Applications Like G-Mail That Use Lower Bandwidth And Offer Snappier User Response.
Safari Warning
Steve Jenson Suggests That The Safari Implementation IS Completely Hobbled In That It Can Only DO Get and Post, this Is Clearly INADEQUATE, Hopefully this Will Be fixed in Future Versions.
Opera Warning
Opera 7.6 preview 1, is currently rather broken, it has a basic implementation of the object - you'll see that it's full of bugs such as double results and missing methods to set or get the headers, rendering it not as useful, again I 'm sure this will come up to standard soon. Opera 8 beta 1 has not fixed all these bugs, but it's getting better. Because of Repeated ReadyState 4 events you should never assume each request results in only one Complete response, so if you Code Anything That Adds in. Complete Event you should use a flag to ensure That Each Request Hasn't Already Been ACTED ON.WHY XML HTTP REQUEST OBJECT?
Whilst the object is called the XML HTTP Request object it is not limited to being used with XML, it can request or send any type of document, although dealing with binary streams can be problematical in javascript.
Creating the object
In Internet Explorer, you create the object using new ActiveXObject ( "Msxml2.XMLHTTP") or new ActiveXObject ( "Microsoft.XMLHTTP") depending on the version of MSXML installed. In Mozilla and Safari (and likely in future UA's that support it) You use new xmlhtpRequest ()
This means that you need to show different script to different browsers, as what works in one, will error in another. The script below does this, and if it's not supported, the variable is set to false to allow for appropriate error messages and recovery with degrading to more normal HTTP transaction methods when the object is not available. This degradation is important, even in IE the objects can often be blocked by slightly raised security settings (popular due to the commonly exploited holes of course). Where possible degrade , some approaches are talked about below, if you really can not, I'd recommend providing an alternative page aswell. GMail for example has said they'll be providing a less demanding version in the future, hopefully with no javascript at all, Full Degradation.var Xmlhttp = FALSE;
/ * @ cc_on @ * /
/ * @ IF (@_jscript_version> = 5)
// JScript Gives US Conditional Compilation, We can Cope with Old IE Versions.
// and security blocked creeion of the objects.
Try {
XMLHTTP = New ActiveXObject ("msxml2.xmlhttp");
} catCH (e) {
Try {
XMLHTTP = New ActiveXObject ("Microsoft.xmlhttp");
} catCH (e) {
XMLHTTP = FALSE;
}
}
@END @ * /
IF (! xmlhttp && typeof xmlhtpRequest! = 'undefined') {
Xmlhttp = new xmlhttpRequest ();
}
How do i make a request?
Making a HTTP request is very simple. You tell the XML HTTP request object what sort of HTTP request you want to make and which url you want to request. Provide a function to be called when as the request is being made, and finally what, (if any) Information you want Sent Along in the body of the request.
The following script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete , IT Displays the responsext to the user with an alrt.xmlhttp.open ("get", "test.txt", true);
XMLHTTP.ONREADYSTATECHANGE = function () {
IF (xmlhttp.readyState == 4) {
Alert (XMLHTTP.Responsext)
}
}
Xmlhttp.send (null)
Making a head request
With a HEAD request, a server will only return the headers of a resource, rather than the resource itself, this means you can find out the Content-Type or Last-Modified of a document, without downloading it itself.
A Typical Head Request Might Return Something Like this:
HTTP / 1.1 200 ok
Server: Microsoft-IIS / 4.0
Cache-control: max-agn = 172800
Expires: Sat, 06 Apr 2002 11:34:01 GMT
Date: Thu, 04 APR 2002 11:34:01 GMT
Content-Type: Text / HTML
Accept-ranges: Bytes
Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT
ETAG: "0A7ccac50cbc11: 1AAD"
Content-Length: 52282
To make A Head Request, You Simply Replace The First Parameter with Head, And The Extract The Headers, Either Using GetallResponseHeaders or getResponsehead ("name") To get anore.
Xmlhttp.open ("Head", "/faq/index.html" ,true);
XMLHTTP.ONREADYSTATECHANGE = function () {
IF (xmlhttp.readyState == 4) {
Alert (Xmlhttp.GetallResponseHeaders ())
}
}
Xmlhttp.send (null)
Using Head Requests, To Find The Last-Modified of Another File.
One Use of Head Requests, Is To Find Out When A Url Was Modified, Extending The Previous Example, You Get Something Like this:
Xmlhttp.Open ("Head", "/faq/index.html", true); Xmlhttp.onReadyStateChange = function () {
IF (xmlhttp.readyState == 4) {
Alert ("File Was Last Modified ON -"
XMLHTTP.GETRESPONSEHEADER ("Last-Modified"))))
}
}
Xmlhttp.send (null)
To Format The Date Differently, or Use Something Other Than Alert, The JavaScript FAQ Will Tell You More.
Does a URL EXIST?
Another simple use is finding if a url exists, in HTTP there are various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and the others mean other things. See HTTP status codes for a full explanation. Using The Status Property of The Xmlhttp Object Provides you this status
Xmlhttp.open ("Head", "/faq/index.html" ,true);
XMLHTTP.ONREADYSTATECHANGE = function () {
IF (xmlhttp.readyState == 4) {
IF (xmlhttp.status == 200) Alert ("URL EXISTS!")
Else IF (xmlhttp.status == 404) Alert ("Url Doesn't Exist!")
Else Alert ("status is" xmlhttp.status)
}
}
Xmlhttp.send (null)
Calling a Server-Side Script without refreshing the page
Forms are the way to "call" serverside scripts in HTML, they force the page reload, and this is often not very user friendly. Using the HTTP Request, you can call the script without refreshing the page, and still the form have "fallback "To working when the xml http request object is not available.
<%
A = (Request.QueryString ('A') '')
B = (Request.QueryString ('b') '')
IF (ISNAN (a) || isnan (b)) {a = ''; b = '; total =' '}
Else {
Total = a b
}
ACC = Request.ServerVariables ('http_accept') '' 'f (ACC.INDEXOF (' Message / X-JL-FormResult ')! = - 1) {
Response.write (Total)
} else {
%>