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:
<section> <!-- content here --> </section> <main> <!-- content here --> </main> <section> <!-- content here --> </section> <div class="modal"> <!-- content here --> </div> <div class="loader"> <!-- content here --> </div>
The markup for the main
element is shown below:
<main> <h2>Popular front-end frameworks</h2> <p>Click each one to load details via AJAX.</p> <div class="boxes"> <a href="#">Bootstrap</a> <a href="#">Foundation</a> <a href="#">UIkit</a> <a href="#">Semantic UI</a> <a href="#">Skeleton</a> <a href="#">Material Design Lite</a> </div> </main>
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:

Modal Markup
The next step is to examine the structure of our modal. Here’s the HTML code:
<div class="modal"> <button class="close" aria-label="Close">✕</button> <div class="m-content"> <ul class="m-info"> <li>Framework</li> <li></li> <li>Current Version</li> <li></li> <li>Number of Github Stars</li> <li></li> <li>Official Page</li> <li></li> </ul> <p class="m-message"></p> </div> </div>
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:

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:
.modal { opacity: 0; } .loader { display: none; }
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:
[ { "url": "http://getbootstrap.com/", "numberOfStars": "88.260+", "currentVersion": "3.3.5", "name": "Bootstrap" }, { "url": "http://foundation.zurb.com/", "numberOfStars": "21.180+", "currentVersion": "5.5.3", "name": "Foundation" }, // 4 more objects here ]
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:
var $list = $('.m-info'), var $message = $('.m-message'); var $modal = $('.modal'); var $loader = $('.loader'); var $framework;
Now, it’s time to examine the code responsible for the execution of the request:
$('.boxes a').on('click', function(e) { e.preventDefault(); $framework = $(this).text(); $.ajax({ url: 'Demo.json', dataType: 'json', beforeSend: function() { $loader.show(); } }).done(successFunction) .fail(errorFunction) .always(alwaysFunction); });
You’ll notice the syntax for the ajax
function looks as follows:
$.ajax([settings])
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:
function successFunction(data) { if (data.length > 0) { for (var i = 0; i < data.length; i++) { if ($framework === data[i].name) { $list.show(); $message.hide(); $list.find('li:nth-of-type(2)').text($framework); $list.find('li:nth-of-type(4)').text(data[i].currentVersion); $list.find('li:nth-of-type(6)').text(data[i].numberOfStars); $list.find('li:nth-of-type(8)').html('' + data[i].url + ''); break; } else { $list.hide(); $message.show().text('No data received for this framework!'); } } } else { $list.hide(); $message.text('No data received from your respose!'); } }
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:
function alwaysFunction() { $loader.hide(); $modal.addClass('active'); }
The active
class looks like this:
.active { opacity: 1; z-index: 10; transform: scale(1); }
Below you can see the expected appearance of the modal if we click on the Bootstrap
text link:

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 themain
element. For example, let’s assume that we define a URL where the value of thename
property of the object that is related to the Foundation framework isFoundation2
instead ofFoundation
. In such a case, if we click on theFoundation
text link, the modal below will appear:

- 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:

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:
function failFunction(request, textStatus, errorThrown) { $list.hide(); $message.text('An error occurred during your request: ' + request.status + ' ' + textStatus + ' ' + errorThrown); }
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:

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).
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.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post