Advertisement
  1. Web Design
  2. HTML/CSS
  3. JavaScript for Designers

An Example of AJAX With Vanilla JavaScript

Scroll to top
This post is part of a series called AJAX for Front-End Designers.
An Introduction to AJAX for Front-End Designers
A Beginner’s Guide to AJAX With jQuery

Following on from our introduction to AJAX, here’s an example which uses the XMLHttpRequest API to initialize an AJAX request.

AJAX Example

Have a look at the following basic structure:

1
2
      
3
          
4
          Learn more about Einstein
5
          
6
      

Also, consider the related visualization:

filefilefile

Here’s what we want to happen: when we click on the button, an AJAX request will be executed. Then, the element with the bio id will appear and its content will be populated with the response data. That data is static and stored in the Bio.txt file.

Note: the file is uploaded to the Codepen server. In this way, we avoid cross-origin problems which may occur.

Below is the required AJAX code:

1
2
      var btn = document.getElementById('request');
3
      var bio = document.getElementById('bio');
4
5
      var request = new XMLHttpRequest();
6
7
      request.onreadystatechange = function() {
8
        if(request.readyState === 4) {
9
          bio.style.border = '1px solid #e8e8e8';
10
          if(request.status === 200) { 
11
          	bio.innerHTML = request.responseText;
12
          } else {
13
          	bio.innerHTML = 'An error occurred during your request: ' +  request.status + ' ' + request.statusText;
14
          } 
15
        }
16
      }
17
18
      request.open('Get', 'Bio.txt');
19
20
      btn.addEventListener('click', function() {
21
        this.style.display = 'none';
22
        request.send();
23
      });

Broken Down Into Steps

Let’s now describe the steps for this request:

  • Create an XMLHttpRequest object.

  • Write the function that will run when the server sends back the response data. The XMLHttpRequest object has the onreadystatechange property which stores this function. Every time the state of the request changes, this callback function is executed.

  • Monitor a few other properties of the XMLHttpRequest object. First, the readyState property specifies the state of our request. Throughout the AJAX call its value changes and can receive values from 0 to 4 (e.g. the value 4 means that the response data is available to us). Second, the status property indicates whether the request is successful or not (e.g. the value 200 defines a successful request). In this example, assuming that we retrieve the response data and the AJAX call is successful, we update the content of the target element. Otherwise, we display a message with information extracted from the XMLHttpRequest object.

  • Specify the type of the request by using the open method. This method accepts two required parameters and three optional ones. The first required parameter defines the HTTP method (e.g. GET or POST). The second one determines the URL to which we’ll send the request. Optionally, we pass a third boolean parameter which indicates whether the request is asynchronous (i.e. default true value) or synchronous. The other two optional parameters can be used for authentication purposes.

  • Submit the request when the button is clicked via the send method. Plus, at this point we hide the button.

Note: If you really need to support very old versions of Internet Explorer (i.e. IE6 and below), you have to create an instance of the ActiveXObject object (see Step 1 section).

The next visualization shows the body of our request as it is printed in the browser’s console.

filefilefile

The final demo looks like this:

filefilefile

On the other hand, if we request a file which doesn’t exist, we’ll see a message similar to the following:

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

Here’s the embedded Codepen demo:

Conclusion

In this tutorial we explored how we can implement a straightforward AJAX request using vanilla JavaScript.

In the next part of this series, we’ll focus on jQuery’s AJAX-related functions and methods. Then, in the final part of the series, we’ll work with a more complicated example. Stay tuned!

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.