AJAX

This article will show us how to use AJAX with Vanilla JS.

I. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML.

AJAX is a web technology that helps us create dynamic web pages without reloading the page. It sends and receives data asynchronously and doesn’t interfere with the current webpage.

Nowadays, we mostly use JSON instead of XML because JSON is faster and easier to work with.

II. How AJAX works

AJAX is a set of web development techniques. This set of systems includes:

  • HTML/XHTML as the primary language and CSS for styling.
  • The Document Object Model (DOM) for dynamic data visualization and interactive creation.
  • XML or JSON for data exchange.
  • XMLHttpRequest object for asynchronous communication.
  • JavaScript as the programming language to connect all of the above technologies.

Operation flow

  • The browser makes a JavaScript call to trigger the XMLHttpRequest.
  • In the background, the browser makes an HTTP request to the server.
  • The server receives, retrieves, and sends back the data to the browser.
  • The browser receives data from the server and immediately displays it on the page. No need to reload the whole page.

III. XMLHttpRequest object

XMLHttpRequest object is an API to transfer data between a web browser and a web server. It’s provided by the browser environment.

XMLHttpRequest can operate on any data, not only in XML formats, such as JSON or plain text.

Create a request

To make the request, we need to:

Step 1: Create XMLHttpRequest

let xhr = new XMLHttpRequest();

The constructor has no arguments.

Step 2: Initialize it

xhr.open(method, URL, [async, user, password])
  • method: HTTP methods such as “GET” or “POST”.
  • URL: the URL to request.
  • async: We set it as true, so the request is asynchronous.
  • user, password: login and password for basic HTTP auth if needed.

Step 3: Send XHR object

xhr.send();

Example:

document.getElementById('button').addEventListener('click', loadUsers);

// Load Github Users
function loadUsers(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.github.com/users', true);

    xhr.onload = function() {
        if(this.status == 200){
            var users = JSON.parse(this.responseText);
            console.log(users);
        }
    }

    xhr.send();
}