Lesson 2: Working with web services CHAPTER 8 375
You can use a more concise way to write this code with the $.get() method instead or, bet-
ter yet, use the $.getJSON() method, as shown in the following example.
function addNumbers() {
var x = $('#x').val();
var y = $('#y').val();
var data = { "x": x, "y": y };
$.getJSON('/addition', data, function (data) {
$('#result').html(data.result);
});
}
The size of the addNumbers function has dropped substantially! This is a good time to
implement the other math functions. For the implementation of the other functions, the
HTML page has buttons added as follows.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/scripts/default.js"></script>
</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>
<button id=”btnSubtract” type=”button”>Subtract</button>
<button id=”btnMultiplication” type=”button”>Multiplication</button>
<button id=”btnDivision” type=”button”>Division</button>
</form>
</body>
</html>
At the top of the default.js file, code is added to subscribe to the button click events for
the new buttons, as shown in the following code example.
$(document).ready(function () {
$('#btnAdd').on('click', addNumbers)
$('#btnSubtract').on('click', subtractNumbers)
$('#btnMultiplication').on('click', multiplyNumbers)
$('#btnDivision').on('click', divideNumbers)
});
For the subtractNumbers function, you can use the $.post() method where the HTTP POST
method is required. For the multiplyNumbers function where the HTTP PUT method will be
used, and for the divideNumbers function where an HTTP DELETE method will be used, the
$.ajax() method will be called. The following code example demonstrates these functions, but
they won’t work until the app.js file is updated to accept these calls.
function subtractNumbers() {
var x = $('#x').val();