- Introduction
- Common Properties and Methods
- Where To Start
- Creating the Request Object
- Making the Request
- Custom Loading and Error Handling Messages
- Parsing the Response
- Assessing Your Needs
- Conclusion
Custom Loading and Error Handling Messages
The event handler that you created for the onreadystatechange method is the place to focus on loading and error handling. This is the time to start thinking of the users and provide feedback about the status of the content with which they're interacting. In the example, I provide feedback for all the loading status codes and some basic feedback for the error handling status codes that occur most frequently. To indicate the current state of the request object, the readyState property includes the values shown in the following table.
Value |
Description |
0 |
Uninitialized. The object is not initialized with data. |
1 |
Loading. The object is loading its data. |
2 |
Loaded. The object has finished loading its data. |
3 |
Interactive. The user can interact with the object even though it's not fully loaded. |
4 |
Complete. The object is completely initialized. |
The W3C has quite a long list of the HTTP status code definitions. I chose two status codes:
- 200: The request has succeeded.
- 404: In case the server hasn't found anything matching the requested file.
Finally, I check for any other status codes that would produce an error and provide a general error message. Following is an example of the code that you could use to handle these situations. Notice that I'm targeting the div ID that we created in the body of the HTML file and applying the loading and/or error messages to it with the innerHTML method, which sets the HTML between the start and end tags of the div object:
if(obj.readyState == 0) { document.getElementById('copy').innerHTML = "Sending Request..."; } if(obj.readyState == 1) { document.getElementById('copy').innerHTML = "Loading Response..."; } if(obj.readyState == 2) { document.getElementById('copy').innerHTML = "Response Loaded..."; } if(obj.readyState == 3) { document.getElementById('copy').innerHTML = "Response Ready..."; } if(obj.readyState == 4) { if(obj.status == 200) { return true; } else if(obj.status == 404) { // Add a custom message or redirect the user to another page document.getElementById('copy').innerHTML = "File not found"; } else { document.getElementById('copy').innerHTML = "There was a problem retrieving the XML."; } }
When the status code is equal to 200, meaning that the request has succeeded, the response is ready to be parsed.