Archive for June 6, 2007

JavaScript XMLHttpRequest onreadystatechange for Ajax Requests

Posted in JavaScript, Software, Web, internet, programming on June 6, 2007 by Joey

After an XMLHttpRequest (XHR) object has been created, the open method has been called on a URL against the XHR object and the URL has been sent to a web server, the next step is to listen for a response. This is done via the onreadystatechange property of the XMLHttpRequest object, as follows:

objXHR.onreadystatechange = function(evt){
if (objXHR.readyState == 4) {
if(objXHR.status == 200)
//Handle processing here
else
document.write('Error processing request');
}
};
objXHR.send(null);

Possible readyState values are:

0 = open has not yet been called
1 = send has not yet been called but open has been called
2 = send has been called but no response from server
3 = data is in the process of being received from the server
4 = response from server has arrived