AJAX & Prototype Page 2 - Ajax Features Needed to Build Active Client Pages |
Before sending data to the server, we have to explain four important properties of the XMLHttpRequest object. The onreadystatechange Property After a request to the server, we need a function that can receive the data that is returned by the server. The onreadystatechange property stores the function that will process the response from a server. The following code defines an empty function and sets the onreadystatechange property at the same time: xmlHttp.onreadystatechange=function() { //This function processes the response from the server } The readyState Property The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
The status Property This property 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. We are going to add two if-statements to the onreadystatechange function to test whether our response is complete (this means that we can get our data) or if an error occurred: xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { if(xmlHttp.status==200) { // Receive the data from the server and do whatever. } else alert(There is a problem with the data at the server); } } In this way you check whether the response is complete. The response may be complete, but there is an error. So inside the block, you check whether the request was successful. If it was not, you give a generalized error message concerning the page as I have given. Unfortunately, “xmlHttp.status” may not work with your browser. If that is the case, you will not use this if-else condition. You will still need to receive the data here. The problem now is, how do you detect if an error has occurred? Luckily the XMLHttpRequest has an abort() method and the DOM has a timer function. After sending the request, you can set the timer function that will abort the request if the readyState property does not indicate 4, after some expected time. For simplicity I will assume that the readyState property will indicate 4 within a reasonable amount of time and I will not address the error and timing issue anymore in this series.
blog comments powered by Disqus |
|
|
|
|
|
|
|