XMLHttpRequest Object
XMLHttpRequest Object in Ajax
An object of XMLHttpRequest is used for asynchronous communication between client and server.
It performs following operations:
- Sends data from the client in the background.
- Receives the data from the server.
- Updates the webpage without reloading it.
Properties of XMLHttpRequest object
Property | Description |
---|---|
onReadyStateChange | It is called whenever readystate attribute changes. It must not be used with synchronous requests. |
readyState | represents the state of the request. It ranges from 0 to 4.
|
Methods of XMLHttpRequest Object
The important methods of XMLHttpRequest object are as follows:
Property | Description |
---|---|
void open(method, URL) | opens the request specifying get or post method and url. |
void open(method, URL, async) | same as above but specifies asynchronous or not. |
void open(method, URL, async, username, password) | same as above but specifies username and password. |
void send() | sends get request. |
void send(string) | send post request. |
setRequestHeader(header,value) | it adds request headers. |
All modern browsers support the XMLHttpRequest object (Except IE5 and IE6 use an ActiveXObject).
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
Syntax
variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
Example
variable=new ActiveXObject("Microsoft.XMLHTTP");
To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject.