Lesson 2: Working with web services CHAPTER 8 371
Now that the code is operational, you might want to execute the AJAX call asynchronously.
You can do this by locating the open method call and changing the false to true. However,
because that setting causes a thread to be created and the send method to be called, the
code won’t wait for the result to be returned. Instead, the program continues to the next
line of code, where it attempts to process the result even though the result might not have
arrived from the server. To handle the asynchronous call, you must subscribe to the onready-
stateschange event, which is triggered whenever the state of XMLHttpRequest changes. If the
ready state changes to 4, the call has completed, but you must also test the HTTP status code
to ensure that no error has occurred by verifying that the return code is 200. The following is
the modified addNumber function that correctly handles the asynchronous call.
function addNumbers() {
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var result = document.getElementById('result');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonObject = JSON.parse(xmlhttp.response);
result.innerHTML = jsonObject.result;
}
}
xmlhttp.open("GET", "/addition?x=" + x + "&y=" + y , true);
xmlhttp.send();
}
You might be wondering what the number 4 means. The following is a list of the
readyState codes.
■■0 Uninitialized The open method has not been called yet.
■■1 Loading The send method has not been called yet.
■■2 Loaded The send method has been called; headers and status are available.
■■3 Interactive Downloading; the response properties hold the partial data.
■■4 Completed ll operations are finished.A
As these values show, you need to subscribe to the onreadystatechange event before you
call the open method.
Handling progress
If the server provides progress events, you can subscribe to the progress event at the browser.
You can add an event listener to subscribe to the progress event and execute code each time
the event is triggered, as shown in the following code.
function addNumbers() {
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var result = document.getElementById('result');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {