AJAX XMLHttpRequest Properties

onreadystatechange

Before you calling send method, Using onreadystatechange event to set callback (handler) function to be executed when the status of the request changes,

Syntax

 xhr.onreadystatechange = function() {     ...... };

readyState

readyState property returns the status of the request.

Different States

Constant Name State Value Description
UNSENT 0 uninitialized open() method has not been called.
OPENED 1 unsend send() method has not yet been called.
HEADERS_RECEIVED 2 send send() method has been called and headers and status data are available.
LOADING 3 receiving Data receiving from server and responseText holds the receiving data.
DONE 4 completed Ajax request finished.

Syntax

 var current_state = xhr.readyState;

Example You can use either constant name or state value.

 xhr.onreadystatechange = function() {     if (xhr.readyState == 4) {         alert(xhr.responseText);      } };

 xhr.onreadystatechange = function() {     if (xhr.readyState == xhr.DONE) {         alert(xhr.responseText);      } };

Alternative way, If you concern about only state = 4 (DONE), use the onload event.

 xhr.onload = function() {     ... };

status

When a request is received on server, Server return the HTTP status code using status property. for example, status code 200 for Ok, 408 for Request timeout, 404 for Request not found.

Syntax

 var xhr_status = xhr.status;

Example

 if (xhr.readyState == xhr.DONE){     if ((xhr.status == 200) || (xhr.status == 0)){         alert(xhr.status);     } }

statusText

Same as above server return HTTP status string Request ok for 200, Request timeout for 408, Request not found for 404.

Syntax

 var xhr_statustext = xhr.statusText;

Example

 if (xhr.readyState == xhr.DONE){     if ((xhr.status == 200) || (xhr.status == 0)){         alert(xhr.statusText);     } }

responseText/XML/Body

responseText Requested response return as a string data as a string object.

Example

 var xhr_responseText = xhr.responseText;

responseXML Requested response return as a XML data as a XML object.

Example :

 var xhr_responseXML = xhr.responseXML;

responseBody This property is use when XHR object created as a ActiveX component (for IE 5 & 6).

Example

 var xhr_responseBody = xhr.responseBody;