After the XHR object has been created and the request has been made, we need a way to know when the response has been received. This is where the onreadystatechange event handler is used. The onreadystatechange event handler fires when the state of the request object changes and allows us to set a callback method to be triggered. After this callback method is triggered, it is up to us to handle the response. The custom callback method named onResponse, shown in Listing 2.1, will be covered in Chapter 3, where we will cover all aspects of an Ajax response.
Listing 2.1. Sending a Request
Listing 2.2 is a custom method named checkReadyState that checks the ready state of the XHR object and handles each state in a separate branch based on the number that the current state equals. This custom method will be called from the onResponse method to determine the ready state of the XHR before it handles parsing the response object.
Listing 2.2. Determining the readyState Value
Notice that there are two parameters in this method. The first parameter; named obj, is the XHR object that made the request and is now being used to check the readyState status of the response from the server. The different numbers that are returned in relation to the readyState are listed in Table 2.3 with a definition for each.