370 CHAPTER 8 Websites and services
In the math web service, the result is not XML; it’s JSON, so the last line of code needs to
change. In addition to having a responseXML property, the XMLHttpRequest object has a
response property that is a string. The response string needs to be converted to an object,
and the JSON.parse method can accomplish the task. In addition, the URL must be pieced
together by taking the values from text boxes to build this QueryString. The following code
can be added to the default.js file to make the AJAX call.
$(document).ready(function () {
$('#btnAdd').on('click', addNumbers)
});
function addNumbers() {
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var result = document.getElementById('result');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/addition?x=" + x + "&y=" + y , false);
xmlhttp.send();
var jsonObject = JSON.parse(xmlhttp.response);
result.innerHTML = jsonObject.result;
}
The first part of this code uses jQuery and adds the subscription to the btnAdd button
after the document is ready. This causes the addNumbers function to execute when the but-
ton is clicked.
The addNumbers function doesn’t use jQuery yet. First, the x and y values are extracted
from the <input> elements. The result variable is set to reference the <span> element whose
id is result. The XMLHttpRequest object is created, and then the open method is executed
with a constructed QueryString. The send method is executed, and the response is parsed to
create an object. Finally, the innerHTML for the result <span> element is populated with the
result property value from the server. To test this page, first execute the following command
to start the web service.
node app
After the web service is running, open the browser and enter the following URL.
http://localhost:8080/Math.html
Enter values in X and Y and click the Add button. You should see the result as shown in
Figure 8-12.
FIGURE 8-12 he AJAX call displaying the proper resultT