ptg16476052
AJAX and jQuery 521
18
XmlHttpRequest to make requests to the server in the background and use the results
within the page.
The Web is based around the concept of pages. When you click a link or submit a form,
usually you leave the page that you’re on and go to a new page with a different URL (or
refresh the current page). AJAX is about retrieving content from the server and then plac-
ing it on the page using JavaScript.
The previous example demonstrated how to use JavaScript to process data entered in a
form and add it to a page instantly. Using AJAX, you can use the same techniques to
retrieve data from the server and add it to the page. It’s possible to write the code neces-
sary to do this sort of thing from scratch, but jQuery makes it a whole lot easier.
Usually, AJAX is associated with server-side applications. For example, you can create a
search engine and then use AJAX to retrieve search results and present them without ever
leaving the current page. Unfortunately, there’s not enough space in this book to teach
you how to create a search engine. jQuery also provides the ability to retrieve informa-
tion from a different static page using AJAX and present it in the current page. I’m going
to present an example that takes advantage of that feature to show you how AJAX can be
used.
Using AJAX to Load External Data
I’ve created a simple page, shown in Figure 18.16, that allows users to look up informa-
tion about South American countries. When a user clicks one of the links, the information
about that country is retrieved from the server and displayed inline on the page.
Because of the way AJAX works, this example will only work if
it’s deployed on a web server. If you load the files directly in your
browser, the JavaScript code that retrieves the information won’t
work. This is because browsers have a security feature that pre-
vents JavaScript on one server from loading content from another
server.
NOTE
The sample consists of two files. The first is the page shown in Figure 18.16, which loads
the da ta from the second page.