O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.4. Using Ajax Shortcuts and Data Types

Problem

You need to make a GET Ajax request to the server and place the contents of the resulting HTML in a <div> with an ID of contents.

Solution

(function($) {
 $(document).ready(function() {
        $('#contents').load('hello-world.html');
});
})(jQuery);

Discussion

This recipe differs slightly from others in that we’ll survey a variety of the functions and shortcuts provided by jQuery in an effort to clearly present their differences.

jQuery provides a number of shortcuts for making Ajax requests. Based upon the previous recipes covering Ajax, the following shortcuts exist: .load(), $.get(), $.getJSON(), $.getScript(), and $.post(). But first, let’s review our solution:

$('#contents').load('hello-world.html');

The .load(url) method is making a GET Ajax request to hello-world.html and placing the contents of that result into the element #contents. Two optional parameters to the .load() method are data and callback. The data parameter can be either a map (or JavaScript object) or as of jQuery 1.3 a string. The following example is passing in the variable hello with the value world. (This is the same as the following URL: hello-world.html?hello=world.)

$('#contents').load('hello-world.html', { hello: 'world' });

The third optional parameter is a callback function that is called when the request completes (either on success or error). In the following example, an alert message is being triggered upon the completion of the request:

$('#contents').load('hello-world.html', ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required