Lesson 2: Working with web services CHAPTER 8 369
</head>
<body>
<form id="mathForm">
Enter X:<input type="text" id="x" /><br />
Enter Y:<input type="text" id="y" /><br />
Result: <span id="result"></span><br />
<button id="btnAdd" type="button">Add</button>
</form>
</body>
</html>
Under the public folder, create a scripts folder and a default.js JavaScript file to con-
tain your code. Add the jQuery library to this folder. You can get the jQuery library from
http://jquery.com if you don’t already have it.
NOTE VERIFY THE JQUERY VERSION
Although jQuery is a fairly stable and mature product, it is still being updated. Be sure that
your script tag references the version of jQuery that you installed.
The Math.html file contains the basic HTML user interface elements needed to collect data
from the user and display a result. In this example, the <form> element isn’t needed because
the form will never be submitted. The <form> element is used only as a means of grouping
the form controls. If the form will be used to submit data to the server, the name attributes of
the form submission elements must be set. In this example, JavaScript and jQuery will be used
to access these elements and make the AJAX call.
Using XMLHttpRequest
The primary object that makes an AJAX call is XMLHttpRequest. As the name implies, this
object certainly can be used to send and receive XML data, but it can also be used to send
and receive other data. In its simplest form, you can use this object as follows.
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","/addition?x=5&y=10",false);
xmlhttp.send();
var xmlDoc=xmlhttp.responseXML;
The first line creates a new XMLHttpRequest object and assigns it to the xmlhttp variable.
The next line sets up the request to use the GET method with a relative URL of /addition
and QueryString of x=5&y=10. The last parameter (false) indicates whether the operation
is to be performed asynchronously when false means that operation is synchronous. The
open method does not communicate to the server; it just sets up the request. The xmlhttp.
send method call communicates to the server. Because the communication in this example is
synchronous, JavaScript execution will not advance to the next line of code until the com-
munication is completed. The next line sets the xmlDoc variable to the xmlhttp.responseXML
property. From there, you can parse the XML as part of processing the results.