This article will show us how to use AJAX with Vanilla JS.
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.
AJAX is a set of web development techniques. This set of systems includes:
Operation flow
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])
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();
}