- Request and Response
- The Ready State
- Request Status
- ResponseText and ResponseXML
The Ready State
The ready state is handled by the callback method, which is set when the request is made. In the sample, the onResponse method is set as the callback and will handle all of the parsing code that we use in this article. We’ll use the following code to check the ready state of the AJAX object in the callback method:
function onResponse() { if(ajax.checkReadyState(’body’, ’loading...’, ’loading...’, ’loading...’) == "OK") { // The parsing code will go here } }
As the code sample shows, we’re passing four parameters to the checkReadyState method. The first is the ID of the div that we want to display the loading message, and the other three are custom loading messages for each state. The div that I choose to use for the loading message is named body, which causes the content and the loading message to toggle each time new data is loaded. Following is the actual checkReadyState method, which handles the code that we just discussed and displays it in the div to which we pass the reference. This method is also included in the sample AJAX engine.
this.checkReadyState = function(_id, _1, _2, _3) { switch(this.request.readyState) { case 1: document.getElementById(_id).innerHTML = _1; break; case 2: document.getElementById(_id).innerHTML = _2; break; case 3: document.getElementById(_id).innerHTML = _3; break; case 4: document.getElementById(_id).innerHTML = ""; return this.http.status(this.request.status); } }
The checkReadyState method is useful for providing feedback to the user about the state of the page. The following table shows the values that it checks.
Value |
State |
0 |
Uninitialized |
1 |
Loading |
2 |
Loaded |
3 |
Interactive |
4 |
Complete |
You can add a custom message for each loading state—from a simple string to an actual image tag in string format; for example, to display an animated pre-loader GIF. Here’s an example of how you would use an image as a loader:
var loader = "<img src=’images/loader.gif’>"; ajax.checkReadyState(’body’, loader, loader, loader);
Not only does the checkReadyState method handle the request state; it includes an HTTP object that checks and returns the status of the request.