374 CHAPTER 8 Websites and services
■■.serialize() Helper method to encode a set of form elements as a string for
submission
■■.serializeArray() Helper method to encode a set of form elements as an array of
names and values
Some of these methods are discussed in later chapters, but you can get more information
at http://jquery.com.
The $.ajax() method is a wrapper for the XMLHttpRequest object that provides a browser-
independent way to write your AJAX call. The $.ajax() method accepts an object parameter
that contains all the settings for the AJAX call. The following code example is a replacement
for the addNumber function.
function addNumbers() {
var x = $('#x').val();
var y = $('#y').val();
var data = { "x": x, "y": y };
$.ajax({
url: '/addition',
data: data,
type: 'GET',
cache: false,
dataType: 'json',
success: function (data) {
$('#result').html(data.result);
}
});
}
In this example, jQuery retrieves the values of x and y. A data variable object is then cre-
ated to hold x and y. The $.ajax() call is executed next; it takes an object argument with all
the settings for the call. In this example, the object is created inline. The url property is set,
and the data is set to the data object created in the previous statement. The type property
is the HTTP method, which supports GET, POST, PUT, and DELETE, but remember that many
firewalls block PUT and DELETE. The cache property is set to false to indicate that the result
should not be cached. The dataType property defines the type of data you expect to receive
from the server and can be set to ‘json’, ‘xml’, ‘html’, ‘script’, ‘jsonp’, or ‘text’.
NOTE CROSS-DOMAIN ACCESS BY USING JSONP
Using JSONP provides cross-domain access to an existing JSON API by wrapping a JSON
payload in a function call. This is considered obsolete; the replacement is to use cross-
origin resource sharing (CORS). CORS is described later in this lesson.
The last property, success, is set to a function to execute when the call returns successful.
This could be a function name that contains the code or, as shown in the example, this could
be an anonymous function with the code. This code runs asynchronously like the previous
XMLHttpRequest code.