Advertisement
  1. Web Design
  2. Ajax
Webdesign

How to Use jQuery’s “ajax” Function

by
Difficulty:IntermediateLength:MediumLanguages:
This post is part of a series called AJAX for Front-End Designers.
A Beginner’s Guide to AJAX with jQuery

Having followed the previous three tutorials, you should have gained a good understanding of AJAX. In this final tutorial, we’ll wrap things up by working with a more involved example.

The Markup

To get an idea of the structure of this example, consider the following markup:

The markup for the main element is shown below:

Notice the text links. These correspond to different front-end frameworks. As we’ll see in the next section, every time we click on the links, an AJAX request will be executed. Then, the element with the class of modal will appear and its content will be updated with data fetched from the response.

Here’s how the main element looks like:

Main_Element

Modal Markup

The next step is to examine the structure of our modal. Here’s the HTML code:

As you can see, the modal contains a few empty elements. We place those in the HTML because their text will change depending on which link we click on and the response that we retrieve.

The image below shows how the modal initially appears:

Modal

By default, the modal is hidden. Additionally, we’ll also hide the loader. This will appear only when the AJAX request is triggered.

Take a look at the corresponding CSS rules:

Note that we use the opacity property (and not the display property) to hide the modal because this property belongs to the animatable CSS properties. In this way, we’ll be able to transition the states of the modal (i.e. the open and closed states).

Generating the JSON Response

For the purposes of this example, we’ll choose to build ourselves the JSON response. Specifically, the expected response (i.e. the Demo.json file) will be an array of objects. Each object will contain details regarding the related front-end frameworks.

Moreover, the value of the name property will match the text links of the main element (see previous section). With that in mind, the structure of the response looks something like this:

Note: the values we’ve used for the numberOfStars and currentVersion properties are fake and purely for the purposes of demonstration.

Similar to the previous examples in this series, we’ll use AJAX to request a static file. However, if we want to embed content coming from other sites (e.g. Google Maps, Flickr), we should read their API documentation, and if necessary, apply for an API key.

Furthermore, our target data lives on the same server as the demo page. Therefore, we’ll avoid limitations that may occur when interacting with third-party services (see the “Limitations of AJAX Requests” section of the first tutorial).

Implementing the AJAX Request

In this section, we’ll use jQuery’s ajax function to initialize an AJAX request. Before doing so, let’s first define our variables by caching the most commonly used jQuery selectors:

Now, it’s time to examine the code responsible for the execution of the request:

You’ll notice the syntax for the ajax function looks as follows:

The settings parameter is a configuration object which holds info about our request. The number of the properties that this object can have is very long (around 34 properties). For the sake of simplicity, we’ll only discuss those that are used in this demo. More specifically:

Property Description
url A string containing the URL to which the request is sent.
dataType The format of the response data (e.g. json, xml, html).
beforeSend A callback function that is executed before we send the request. Here, this function triggers the code that shows the loader.

Before we move on, it’s worth mentioning three things:

  • There’s also another syntax for the ajax function: $.ajax(url[, settings])
  • All the configuration properties of the settings parameter are optional.
  • The default HTTP method is GET.

Promise Methods

The ajax function returns the jQuery XMLHttpRequest or jqXHR object. This object implements the Promise interface, and thus it contains all the properties, methods, and behavior of a Promise.

In this example, we use the following Promise methods:

The done method is triggered if the request succeeds. It receives one or more arguments, all of which can be either a single function or an array of functions. For instance, in our demo, the successFunction() is passed as an argument.

The callback function (e.g. successFunction()) accepts three arguments. First, the returned data. Second, a string categorizing the status of the request (see the previous article for its possible values). Lastly, the jqXHR object.

The fail method is called if the request fails. It receives one or more arguments, all of which can be either a single function or an array of functions. For instance, in our demo, the errorFunction() is passed as an argument.

The callback function (e.g. errorFunction()) accepts three arguments: the jqXHR object, a string categorizing the status of the request, and another string which specifies the resulting error. This error receives the textual portion of the HTTP status, such as Not Found or Forbidden.

The always method is executed when the request finishes, regardless of the success (i.e. the done method is executed) or failure (i.e. the fail method is executed) of it. Again, it receives as an argument a single function or an array of functions. For instance, in our demo, the alwaysFunction() is passed as an argument.

The state of the request specifies the function’s arguments. In case of a successful request, the callback (e.g. alwaysFunction()) receives the same arguments as the callback of the done method. On the contrary, if the request fails, it accepts the same arguments as the callback of the fail method.

Note: Instead of the done, fail, and always Promise methods that are used in this example, we could equally have used the success, error, and complete callback functions. These functions are defined in the settings parameter.

Displaying the Data

If the request succeeds, we’re able to get back the response data. Then, we manipulate it so as to populate the empty elements of the modal.

Consider the code for the successFunction callback:

Although we updated the content of our modal, this is still hidden. It becomes visible and the loader disappears when the request finishes. Only then, the alwaysFunction callback is executed:

The active class looks like this:

Below you can see the expected appearance of the modal if we click on the Bootstrap text link:

success_jQuery

A Couple of Scenarios

It’s important to understand the code that is executed under certain circumstances. Let’s cover two common scenarios:

  • The value of the name property doesn’t match the text links of the main element. For example, let’s assume that we define a URL where the value of the name property of the object that is related to the Foundation framework is Foundation2 instead of Foundation. In such a case, if we click on the Foundation text link, the modal below will appear:
Error_Modal
  • The response data is empty. Say, for instance, that we define a URL which points to an empty array. In this case, the modal would look like this:
Empty_Response

Handling Errors

So, we’ve covered the code that is fired when the request succeeds. But what happens if the request fails? In the case of an unsuccessful request, we hide the list and show a custom message.

Here’s the code of the failFunction() which demonstrates that behavior:

To familiarize ourselves with this code, we specify a URL that doesn’t exist. Hence, the fail method will be triggered and the modal below will be shown:

Fail_Modal

Note: Again, the error message might be different if you run this example locally.

Here’s the embedded Codepen demo:

Conclusion

In this tutorial we concluded our examination of AJAX from a web designer’s perspective–well done for following it through! I hope that you found this series helpful and you learned some new skills.

As a next step, I encourage you to examine the following things:

  • Become familiar with jQuery’s AJAX shorthand methods that we didn’t cover (e.g. $.getJSON method).
  • Implement your own AJAX requests by accessing either static files or even dynamic data coming from third-party services (e.g. Flickr).
Advertisement
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.