An Introduction to jQuery’s Shorthand Ajax Methods

Aurelio De Rosa
Share

Raise your hand if you’ve never heard the term Ajax. I’ll bet almost all of you have your arms down, close to their body. Ajax, which originally stood for Asynchronous JavaScript and XML, is one of the most used client-side methodologies, helping to create asynchronous websites and web applications.

Performing Ajax calls using raw JavaScript is of course possible, but dealing with all the different parts of the code can be a pain. This is even more true if you have to support a prehistoric browser like Internet Explorer 6.

Fortunately for us, jQuery provides a set of methods that deal with these issues for us, allowing us to focus on the task we want accomplish with the code. jQuery offers a primary method, called $.ajax(), which is highly configurable to fit whatever need you may have. It also provides a set of shorthand methods, called shorthand because they are simply wrappers for the $.ajax() method with a preset configuration, each serving a single purpose.

All except the $.ajax() method have one feature in common: they don’t operate on a set of DOM elements, but are called directly from the jQuery object. So, instead of having a statement like:

$('p').ajax(...);

which selects all the paragraphs in the page and then calls the ajax() method, we’ll write:

$.ajax(...);

In this article, we’ll discuss three of the most used jQuery shorthand methods: load(), $.post(), and $.get().

load()

The first method we’ll discuss is load(). It enables us to load data from the server and place the returned data (often HTML code) into the elements matched by the selection. Before seeing it in action, let’s see its signature:

load(url[, data][, callback])

The meaning of each parameter is described below:

  • url: A string specifying the URL of the resource to which you want to send the request;
  • data: An optional string that should be a well formatted query string or an object that has to be passed as the request parameter. In case a string is passed the request method will be GET, if an object is passed the method of the request will be POST. If this parameter is omitted the GET method is used;
  • callback: An optional callback function invoked after the Ajax request is complete. This function accepts up to three parameters: the response text, a status string of the request, and the jqXHR instance. Inside the callback, the context (this) is set to each element of the collection, one at a time.

Does this seem difficult to use? Let’s see a concrete example.

Imagine you have an element in your website having an ID of main that represents the main content. What we want to do is asynchronously load the main content of the pages referenced by the links in the main menu, which ideally has main-menu as its ID. We want to retrieve only the content inside this element because the other parts of the layout don’t change, so they don’t need to be loaded.

This approach is intended as an enhancement because if the user visiting the website has JavaScript disabled, they will still be able to browse the website using the usual synchronous mechanism. We want to implement this feature because it can improve a website’s performance. In this example we’re assuming that all the links in the menu are internal links.

Using jQuery and the load() method, we can achieve this task with the following code:

$('#main-menu a').click(function(event) {
      // Prevents the default behavior which is
      // to load the page synchronously
      event.preventDefault();

      // Load the HTML code referenced by this.href
      // into the element having ID of #main
      $('#main').load(this.href);
   });

But wait! Can you see anything wrong with this code? Some of you might notice that this code retrieves all the HTML code of the referenced page, not just the main content. Executing this code results in a situation similar to having two mirrors, one in front of the other: you see a mirror inside a mirror inside a mirror, and so on. What we really want is to load only the main content of the targeted page.

To fix this issue, jQuery allows us to add a selector immediately after the specified URL. Using this feature of the load() method, we can rewrite the previous code as:

$('#main-menu a').click(function(event) {
      event.preventDefault();

      $('#main').load(this.href + ' #main *');
   });

This time we retrieve the page but then we filter the HTML code to only inject the descendants of the element having an ID of main. We’ve included the Universal selector (`*`) because we want to avoid having a #main element inside a #main element; we only want wants inside #main, not #main itself.

This example is nice but it shows only the use of one of the available parameters. Let’s see more code!

Using a Callback with load()

The callback parameter can be used to notify the user about the completion of the action. Let’s update our previous example for the last time, to employ this.

This time we’ll assume we have an element having an ID of notification-bar that will be used as… well, a notification bar.

$('#main-menu a').click(function(event) {
      event.preventDefault();

      $('#main').load(this.href + ' #main *', function(responseText, status) {
         if (status === 'success') {
            $('#notification-bar').text('The page has been successfully loaded');
         } else {
            $('#notification-bar').text('An error occurred');
         }
      });
   });

A live demo of this code, with some minor improvements for the demo, is shown below:

See the Pen jQuery Ajax example with load() by SitePoint (@SitePoint) on CodePen.

Having a grasp of load(), let’s move our attention to the next method.

$.post()

Sometimes we don’t only want to inject the content returned by the server in one or more elements. We may want to retrieve the data and then decide what to do with it after it’s retrieved. To do that, we can use either the $.post() or the $.get() methods.

They are similar in what they do (performing a request to the server), and identical in their signatures and the parameters accepted. The only difference is that one sends a POST request and the other a GET request. Pretty obvious, isn’t it?

In case you don’t recall the difference between a POST request and a GET request, POST should be used if our request has the potential to cause a change in the server-side state, resulting in varying responses. Otherwise it should be a GET request.

The signature of the $.post() method is:

$.post(url[, data][, callback][, type])

The parameters are described below:

  • url: A string specifying the URL of the resource to which you want to send the request;
  • data: An optional string or object that jQuery will send as part of the POST request;
  • callback: A callback function that is executed after the request succeeds. Inside the callback, the context (this) is set to an object that represents the Ajax settings used in the call.
  • type: An optional string to specify how the response body is interpreted. The values accepted are: html, text, xml, json, script, and jsonp. This can also be a string of multiple, space-separated values. In this case, jQuery converts one type into another. For example, if the response is text and we want it to be treated as XML, we can write “text xml”. If this parameter is omitted, the response text is passed to the callbacks without any processing or evaluation, and jQuery does its best to guess the correct format.

Now that you know what $.post() can do and what are its parameters, let’s write some code.

Imagine we have a form to fill out. Every time a field loses focus, we want to send the field’s data to the server to verify that it’s valid. We will assume that the server is returning the information in JSON format. A typical use case is to verify that the username chosen by the user hasn’t already been taken.

To implement this feature we can use jQuery’s $.post() method as follows:

$('input').blur(function() {
      var data = {};
      data[this.name] = this.value;

      $.post(
         '/user',
         data,
         function(responseText) {
            if (responseText.status === 'error') {
               $('#notification-bar').html('<p>' + responseText.message + '<p>');
            }
         }
      );
   });

In this code we’re sending a POST request to the page identified by the relative URL “/user”. We’re also employing the second parameter, data, to send to the server the name and value of the field that’s losing focus. Finally, we’re using a callback to verify that the value of the status property of the JSON object returned is error, in which case we show the error message (stored in the message property) to the user.

To give you a better idea of how a JSON object of this type might look, here’s an example:

{
  "status": "error",
  "message": "Username already in use"
}

A live demo of this code is shown below:

See the Pen Ajax $.post/$.get example by SitePoint (@SitePoint) on CodePen.

Note: The code on CodePen requires the use of a GET request, instead of POST, for the Ajax to work, but the idea still applies.

As I said, except for having the ability to make a GET request, $.get() is identical to $.post(). For this reason, the next section will be pretty short and I’ll focus on some use cases instead of repeating the same information.

$.get()

$.get() is one of the means jQuery provides to make a GET request. This method initiates a GET request to the server using the URL specified and the optional data provided. It can also execute a callback when the request has been completed. Its signature is as follows:

$.get(url[, data][, callback][, type])

The parameters are the same as those of the $.post() method so I won’t repeat them here.

The $.get() function is a good fit for those situations where you have a server always returning the same result for a given set of parameters. It’s also a good choice for resources that you want your users to be able to share. For example, a GET request is ideal for transportation services (like train schedule info) where people searching for the same date and time have to obtain the same result. Besides, if the page is able to respond to a GET request, a user will be able to share the result obtained with a friend — the magic of URLs.

Conclusion

In this article, we’ve discussed some of jQuery’s most used Ajax shorthand methods. They are very convenient methods for doing Ajax requests and, as we’ve seen, in their basic version it’s possible to achieve what we want in just one line of code.

Check out jQuery’s Ajax shorthand docs for more on these and other methods. Although we didn’t discuss the others here, you should be able to use the knowledge you’ve gained in this article to start working with the others too.