An Introduction to jQuery’s Shorthand Ajax Methods

Share this article

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.

Frequently Asked Questions on jQuery Shorthand AJAX Methods

What are the benefits of using jQuery shorthand AJAX methods?

jQuery shorthand AJAX methods offer a more concise and easier-to-read syntax compared to the traditional AJAX methods. They are essentially shortcuts for the more complex AJAX methods, providing a simpler way to make AJAX requests. These methods include .get(), .post(), .load(), and .getJSON(). They are designed to handle specific types of AJAX requests, reducing the amount of code you need to write and making your code cleaner and more efficient.

How does the .get() shorthand method work in jQuery?

The .get() method in jQuery is a shorthand AJAX function that retrieves data from the server using a HTTP GET request. It takes in a URL as a parameter, and optionally, a callback function that runs when the request is successful. The data returned from the server is passed to this callback function. Here’s an example of how to use it:

$.get("test_ajax.txt", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});

What is the difference between .get() and .post() methods in jQuery?

Both .get() and .post() are jQuery shorthand AJAX methods that send HTTP requests to the server and retrieve data. The main difference between them is the way they send data. The .get() method appends data to the URL in a query string, making it suitable for non-sensitive data. On the other hand, the .post() method sends data as part of the request body, making it a better choice for sending sensitive data.

How can I handle errors in jQuery shorthand AJAX methods?

jQuery shorthand AJAX methods do not provide built-in error handling. However, you can use the .fail() method to handle errors. This method is called when the AJAX request fails. It takes a function as a parameter, which is executed when the request fails. Here’s an example:

$.get("test_ajax.txt")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
});

Can I use jQuery shorthand AJAX methods with JSON data?

Yes, jQuery provides a shorthand method specifically for working with JSON data: .getJSON(). This method retrieves data from the server in JSON format using a HTTP GET request. It works similarly to the .get() method, but it automatically parses the returned data as JSON.

How can I use the .load() shorthand method in jQuery?

The .load() method in jQuery is a powerful shorthand AJAX method that loads data from the server and places the returned HTML into the matched elements. It takes a URL and an optional callback function as parameters. Here’s an example:

$("#div1").load("demo_test.txt");

Can I send data to the server using jQuery shorthand AJAX methods?

Yes, you can send data to the server using the .get() and .post() shorthand methods. You can pass the data as an object in the second parameter of these methods. The data is then sent to the server along with the request.

Are jQuery shorthand AJAX methods asynchronous?

Yes, jQuery shorthand AJAX methods are asynchronous by default. This means that the JavaScript does not stop and wait for the AJAX request to complete before moving on to the next statements. This allows for a smoother user experience, as the user can continue interacting with the webpage while the AJAX request is being processed.

Can I use jQuery shorthand AJAX methods with XML data?

Yes, you can use jQuery shorthand AJAX methods to handle XML data. However, unlike with JSON data, there is no specific shorthand method for XML. You would typically use the .get() or .post() method to retrieve the XML data, and then use jQuery’s XML parsing functions to work with the data.

How can I cancel a jQuery shorthand AJAX request?

Unfortunately, you cannot directly cancel a jQuery shorthand AJAX request once it has been sent. However, you can work around this by using the .abort() method on the jqXHR object returned by the $.ajax() method. This is a more advanced technique and is not available with the shorthand methods.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

ajax getajax loadajax postajax shorthandjQueryLouisL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form