JavaScript Kit > JavaScript Reference > Here
Ajax (XMLHttpRequest object)
Ajax is a popular term used to describe asynchronous (versus synchronous) requests made from the client to the server. In JavaScript, Ajax requests are handled using the XMLHttpRequest
object, which lets you open a connection, send the request, then handle the data returned by the server seamlessly in the background.
Related Tutorials
- Performing GET and POST requests using Ajax
- RSS Ajax JavaScript ticker
- Displaying RSS feeds easily using Google Ajax Feed API
- Including the contents of an external page using Ajax
XMLHttpRequest Constructor
All Ajax requests in JavaScript begin by making a call to the XMLHttpRequest
constructor function:
new XMLHttpRequest() //IE7, Firefox, Safari etc
new ActiveXObject("Msxml2.XMLHTTP") //newer versions of IE5+
new ActiveXObject("Microsoft.XMLHTTP") //older versions of IE5+
new XDomainRequest() //IE8+ only. A more "secure", versatile alternative to IE7's XMLHttpRequest() object.
In IE6 and below, the XMLHttpRequest()
is not supported, but instead relies on the proprietary ActiveXObject
for Ajax requests. This makes it necessary to roll your own cross browser HTTP Request constructor function to equalize the differences. Here is one such function you can use:
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
//Usage:
new ajaxRequest()
Once equalized, the returned HTTP request instance shares the same properties and methods across browsers, thankfully.
Note: Any examples below use the custom HTTP request function above as their foundation.
Properties
Properties | Description |
---|---|
readyState |
The "readyState " property keeps track of the current stage of the request by returning an integer:
During each stage of the request, " |
responseText | Returns the response data as a string. |
responseXML |
Returns the response data- assumed to be a valid XML document- as a XML object that can be easily parsed using standard DOM methods. In order for the browser to correctly return an XML object using responseXML , you must ensure the following:
If any one of the above conditions are not met, the data returned will be as plain text, not an XML object as expected. Here's a simple example of returning the first ELEMENT's node value within the XML file "test.xml" using Ajax: var mygetrequest=new ajaxRequest() |
status |
Returns the status code of the request (integer), for example, 404 for a failed request, 200 for a successful one etc. When running your Ajax script online, to test for a fully complete and successful Ajax request, look for a readyState value of 4 plus a status code of 200:
var myrequest=new ajaxRequest() If you're running an Ajax request offline locally on your PC, a value of 0 is returned by var myrequest=new ajaxRequest() |
statusText |
The "natural language" version of the "status " property above, "statusText " returns the status of the request by name rather than by an integer. Here are some "status " codes and their corresponding "statusText " values returned:
|
contentType
IE8 only. Supports this property if using the new |
Allows you to explicitly set/get the contentType of the request, similar to Mozilla's overrideMimeType() method. See new XDomainRequest() on MSDN for more info.
var ie8ajaxrequest=new XDomainRequest() |
timeout
IE8 only. Supports this property if using the new |
Maximum time allowed for the request to complete before the browser aborts the attempt. Fires "ontimeout " when that occurs. See new XDomainRequest() on MSDN for more info.
var ie8ajaxrequest=new XDomainRequest() |
Event handler
Properties | Description |
---|---|
onreadystatechange |
Fires whenever the readyState property changes, allowing you to react to different stages of an asynchronous Ajax request. In some browsers such as Firefox, onreadystatechange fires multiple times while readyState is 3, letting you react as the data is downloading, such as to create a progress bar. IE (as of IE7) only fires onreadystatechange once during readyState of 3.
If your request is synchronous (as specified when calling |
onerror
Mozilla only. IE8 supports this via the new |
Event handler that fires when there is an error with the request. A simpler alternative to using the onreadystatechange event handler plus probing the status property to react to an error. |
onload
Mozilla only. IE8 upports this via the new |
Event handler that fires when the request has completely downloaded. A simpler alternative to using the onreadystatechange event handler plus probing the readyState property to detect when the request is complete. |
onprogress
Mozilla only. IE8 supports this via the new |
Fires multiple times as (large) data is being returned. This lets you display real time progress information to visitors as the data is being downloaded. In Mozilla, the onprogress event handler is inexplicitly passed an event object that contains the following two properties:
For example: var myrequest=new ajaxRequest() |
ontimeout
IE8 only. Supports this property if using the new
|
Fires when an Ajax request has timed out per the "timeout " setting value.
var ie8ajaxrequest=new XDomainRequest() |
Methods
Note: "[]" surrounding a parameter below means the parameter is optional.
Methods | Description |
---|---|
abort() |
Aborts the current Ajax request that's in session. readyState property is reset to 0. Since the XMLHttpRequest() object doesn't have a built-in timer you can use to specify when abort() should be called, you need to build your own. The following aborts an Ajax connection if it has yet to be completed after 5 seconds:
var myrequest=new ajaxRequest() |
open(method, url, [[async], [username], [password]) |
Sets the URL and type of the Ajax request before it is actually sent. The last two optional parameters allow you to pass in a username/password for authenticated requests:
For " var myrequest=new ajaxRequest() Be sure to use encodeURIComponent() on any parameter values that may contain special characters such as spaces or "=" etc. For " As mentioned, by default the browser restricts the domain portion of the URL entered into var myrequest=new ajaxRequest() |
send(data) |
Sends the request to the server with a "data " parameter specifying the body of the request. For "GET " requests, this parameter should be a value of null , while for "POST " requests, the parameters of the request. This method typically should always be called last.
Ajax GET request: var myrequest=new ajaxRequest() Ajax POST request: var myrequest=new ajaxRequest() |
getResponseHeader(header) |
Gets the value of the specified response header of an Ajax request, such as the value for "Content-Type ". The parameter value is case insensitive. It is up to your server to return the anticipated value for a header. You should only call getResponseHeader() after the request is complete based on its readyState property (otherwise it returns a blank string).
Here's an example that probes the content type of the request to decide what data to return: var myrequest=new ajaxRequest() |
getAllResponseHeaders() | Gets the values of all response headers from the Ajax request as one string. You should only call getAllResponseHeaders() after the request is complete based on its readyState property (otherwise it returns a blank string). |
setRequestHeader(header, value) |
Lets you set a header that gets sent along with the request to the server (not to be confused with the header that gets returned by the server). This method MUST be called in between request.open() and request.send() .
For Ajax " var myrequest=new ajaxRequest() |
- JavaScript Operators
- JavaScript Statements
- Global functions
- JavaScript Events
- Escape Sequences
- Reserved Words