(^186) ❘ CHAPTER 7 AJAX
FIGURE 7-1
In the JavaScript fi le, things get under way with adding a click event to the <select> element with
id name addressCountry. Within the handler for the click event, you begin your AJAX request using
jQuery’s $.get() method. The fi rst argument specifi es the path that you want to request, which is
the XML fi le, dynamically substituting the country id in the fi lename. The second argument is a
callback function that you want to execute when your script has received the server’s response, and
the third argument is the type of AJAX request that you want to make. For a complete overview of
the API of the $.get() method, see Appendix G, “AJAX Methods.”The callback method that you specifi ed has one argument specifi ed, xml. This variable contains the
XML data that the server has sent back. This data is then made into a jQuery object, which makes
it much easier to extract data from it:// Make the XML query-able with jQuery
xml = $(xml);The next thing to do is to fetch the ISO2 code from the XML document, which is used to fetch the
updated fl ag for the selected country:// Get the ISO2 value, that's used for the
// file name of the flag.
var iso2 = xml.find('iso2').text();Just as you would do in a normal HTML document, you can use jQuery’s find() method to locate
the XML element <iso2> and retrieve its text content via jQuery’s text() method. In the context of
the three countries I’ve created XML fi les for, the iso2 variable would contain CA for Canada, GB
for the United Kingdom, or US for the United States. The next step is to set the alt and src attri-
butes of the <img> element referencing the country fl ag: