The XMLHttpRequest Object

XMLHttpRequest is an API that facilitates to and fro exchange of data between a client and a server. Here we explore the most commonly used properties and methods of the XMLHttpRequest object.

PROPERTIES

XMLHttpRequest.onreadystatechange

The onreadystatechange property has an event handler which is called everytime the readystatechange event is fired, which in turn is fired every time the readyState attribute of the XMLHttpRequest object changes.

XMLHttpRequest.readyState

The readyState attribute gives the state of the XMLHttpRequest client in integer values from 0 to 4. 0 - uninitialized. 1 - open() method called successfully; connection with server established. 2 - send() method called; HTTP response headers have been received. 3 - data is being received; responseText property holds partial data. 4 - request operation for transfer of data from the server is completed.

XMLHttpRequest.status

status property returns standard HTTP status codes. For example, status value of 200 denotes "Ok" and 404 "Not Found".

XMLHttpRequest.responseText

responseText returns the response data as a string.

XMLHttpRequest.responseXML

responseXML returns the response data as XML.

METHODS

open()

The open() method initializes HTTP/HTTPS requests of the XMLHttpRequest object and can accept upto five parameters.

					
						open(method, url, async, user, password);
					
				

The method parameter can have GET, POST, or HEAD values. The url parameter is the URL to send the request to, either absolute or relative. The async parameter takes a Boolean value: true for asynchronous requests and false for synchronous requests. The user parameter is the name of the user for authentication, but is optional. By default, it is an empty string. The password parameter is another optional parameter for authentication which, by default, is also an empty string.

send()

The send() method sends the request to the server. For GET method, there is no parameter required. But to send data with the request using the POST method, a single parameter containing the data has to be passed to send(), for example, send(name=Spock&planet=Vulcan).