jQuery's Ajax Convenience Methods

Contact Us or call 1-877-932-8228
jQuery's Ajax Convenience Methods

Convenience Methods

If you don't need the extensive configurability of $.ajax, and you don't care about handling errors, the Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. These methods are just "wrappers" around the core $.ajax method, and simply pre-set some of the options on the $.ajax method.

The convenience methods provided by jQuery are:

  • $.get - Perform a GET request to the provided URL.
  • $.post - Perform a POST request to the provided URL.
  • $.getScript - Add a script to the page.
  • $.getJSON - Perform a GET request, and expect JSON to be returned.

In each case, the methods take the following arguments, in order:

  • url - The URL for the request. Required.
  • data - The data to be sent to the server. Optional. This can either be an object or a query string, such as foo=bar&baz=bim.
    • Note: This option is not valid for $.getScript.
    • Also, this parameter is truly optional - if you do not want to supply it, you don't have to supply a placeholder value (jQuery looks at the type of the second parameter to determine if it is your parameters; if the second parameter is a function, it uses it as the success callback described below)
  • success - A callback function to run if the request succeeds. Optional. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
  • dataType - The type of data you expect back from the server. Optional. (Note: This option is only applicable for methods that don't already specify the data type in their name.)

Using jQuery's Ajax Convenience Methods

// get plain text or html
	$.get('/users.php', { userId : 1234 }, function(resp) {
		console.log(resp);
	});

	// add a script to the page, then run a function defined in it
	$.getScript('/js/myScript.js', function() {
		functionFromMyScript();
	});

	// get JSON-formatted data from the server
	// resp will be a single object parsed from the incoming JSON
	$.getJSON('/details.php', function(resp) {
		$.each(resp, function(k, v) {
			console.log(k + ' : ' + v);
		});
	});

$.fn.load

The $.fn.load method is unique among jQuery's Ajax methods in that it is called on a selection. The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s). In addition to providing a URL to the method, you can optionally provide a selector as part of the URL parameter; jQuery will fetch only the matching content from the returned HTML.

Using $.fn.load to Populate an Element

$('#newContent').load('/foo.html');

Using $.fn.load to Populate an Element Based on a Selector

$('#newContent').load('/foo.html #myDiv h1:first', function(html) {
		alert('Content updated!');
	});

Let's look at another example, this time using jQuery's get method:

  1. Navigate on the command line to jQuery/Demos and type npm start to start the Node.js server.
  2. Open http://localhost:8080/UsingXMLHttpRequest-Get.html in a browser.
  3. Open jQuery/Demos/UsingXMLHttpRequest-Get.html in a code editor to review the code.

Code Sample:

jQuery/Demos/UsingXMLHttpRequest-Get.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery get</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#btn').click(function() {
			$.get("Demo", {
					FirstName: "Some",
					LastName: "Othername"
				},
				function(data) {
					var h1 = $(data).find("h1");
					$("#Content").html(h1);
				},
				"xml"
			);
			return false;
		});
	});
</script>
</head>
<body>
	<button id="btn">Start</button>
	<div id="Content"></div>
</body>
</html>

This example is similar to jQuery/Demos/UsingXMLHttpRequest-Ajax.html that we reviewed previously; this time, we'll use jQuery's convenience get method instead of the ajax method. We again use jQuery's ready method to add a listener on the button; when clicked, we invokeget.

The first parameter in our call to $.get, url: "Demo", specifies the remote resource we wish to connect to: http:localhost:8080/Demo. Since this is the get method we are, of course, sending a GET request.

The second parameter passes data to the remote resource - in our case, we pass two GET parameters, so that the full URL is http://localhost:8080/Demo?FirstName=Some&LastName=Othername.

The third parameter is a callback function: as with the previous example, we process the returned XML, finding the contents of the <h1> node and setting div#Contents with its value.

The final parameter, xml, specifies that we expect to receive an XML-formatted response.

Let's have you try out some of the concepts we've reviewed thus far with an exercise, where you can put jQuery to work.

Next