Advertisement
Scroll to top
This post is part of a series called AJAX for Front-End Designers.
An Example of AJAX With Vanilla JavaScript
How to Use jQuery’s “ajax” Function

In the first article of this series, we covered the fundamentals of AJAX. In the second, we looked at a working example using vanilla JavaScript.

In this tutorial, we’ll walk through a few of jQuery’s AJAX-related functions and methods. More specifically, we’ll take a closer look at the shorthand load method and the generic ajax function.

Using the load Method

jQuery’s load method is a simple, yet powerful method for fetching remote data. Below you can see its syntax:

1
2
		$(selector).load(url[, data][, complete])
3
        

The following table shows its possible parameters:

Parameter Description Required
url A string containing the URL to which the request is sent. Yes
data The data (as a string or plain object) that are sent to the server with the request. No
complete A callback function which is executed when the request completes, either successfully or unsuccessfully. No

Here are the parameters of the callback function:

Parameter Description
responseText The data retrieved from the request.
textStatus A string categorizing the status of the request.
jqXHR The jQuery XMLHttpRequest (jqXHR) object, which is a superset of the browser’s native XMLHttpRequest (XHR) object.

The next list summarizes the possible values of the textStatus parameter:

1
  - success
2
  - notmodified
3
  - nocontent
4
  - error
5
  - timeout
6
  - abort
7
  - parsererror

To better understand how the load method works, let’s revisit the example discussed in the previous tutorial.

Once again, look at this straightforward HTML structure:

1
2
      
3
        
4
        Learn more about Einstein
5
        
6
      
7
      

Here’s how that looks:

filefilefile

Remember that we want to update the content of the #bio element with the response data, as soon as the button is clicked.

Here’s the required jQuery code:

1
2
      var $btn = $('#request');
3
      var $bio = $('#bio');
4
5
      $btn.on('click', function() {
6
      	$(this).hide();
7
      	$bio.load('Bio.txt', completeFunction);
8
      });
9
    
10
      function completeFunction(responseText, textStatus, request) {
11
      	$bio.css('border', '1px solid #e8e8e8');
12
      	if(textStatus == 'error') {
13
      		$bio.text('An error occurred during your request: ' +  request.status + ' ' + request.statusText);
14
      	} 
15
      } 
16
      

Assuming that the request is successful (i.e. when textStatus is success or notmodified), the final result would look like this:

filefilefile

Also, consider the following visualization which describes a successful request:

filefilefile

The left part of this visualization shows the XHR object as it is printed in the browser’s console if we use pure JavaScript (see previous tutorial) to make the request. On the other hand, the right part displays the respective jqXHR object as it is printed if we use the load method.

In case of an unsuccessful request, however, a corresponding message should appear. To do so, we monitor the value of the textStatus parameter and display an error message:

filefilefile

Note: If you run the example from your local environment (and store the Bio.txt file in it), the error message will probably be different. For instance, you might see the following result:

filefilefile

Lastly, it‘s worth mentioning that, by default, the load method uses the HTTP GET method, unless we send data as an object to the server. Only then, the POST method is invoked.

See the relevant CodePen demo below:

Now, let’s modify the format of the file that we request from the server. Specifically, for this example, the desired data is included in the Bio.html file instead of the Bio.txt file. Also worth noting: the target file contains two paragraphs.

Assuming that we only want to load the first paragraph, we’ll have to update the initial code as follows:

1
2
      $btn.on('click', function() {
3
          // this line only changes
4
          $bio.load('Bio.html p:first-child', completeFunction);
5
      });
6
      

Here’s how that looks:

filefilefile

And here’s the CodePen demo:

Conclusion

In this tutorial, I demonstrated how you can use AJAX with jQuery. To make things more interesting, we also worked with a couple of practical examples. In the last remaining tutorial of this series we’ll wrap things up by working with a more involved example.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.