JavaScript AJAX (Asynchronous JavaScript and XML) is a technique that gives the ability to send and receive data asynchronously from a web server. AJAX allows you to create rich, responsive user interfaces. It makes it easy to update data on the page without having to reload the entire page. It makes your application more responsive and user-friendly.
I’m going to show you two different ways to make an Ajax request.
XMLHttpRequest
(also known as XHR) object. This object is built into most browsers (even in Internet Explorer) and allows you to send requests and receive responses without having to reload the page.
// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("GET", 'https://jsonplaceholder.typicode.com/users');
// Send the request
xhr.send();
// Fired once the request completes successfully
xhr.onload = function(e) {
// Check if the request was a success
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Get and convert the responseText into JSON
var response = JSON.parse(xhr.responseText);
console.log(response);
}
}
// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("POST", 'https://jsonplaceholder.typicode.com/users', true);
// Set content type
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
// Send the request with data to post
xhr.send(
JSON.stringify({
name : "Jon Doe",
username : "jon-doe",
email : 'jon-doe@unknown.com'
})
);
// Fired once the request completes successfully
xhr.onload = function(e) {
// Check if the request was a success
if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {
// Get and convert the responseText into JSON
var response = JSON.parse(xhr.responseText);
console.log(response);
}
}
fetch()
method is the newer, easier, and best method to make Ajax requests. The fetch()
method returns a promise that can be used to handle the response data. Though, this method won’t work on old browsers like Internet Explorer.
// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/userssss', {
method: "GET",
headers: {
"Content-type": "application/json;charset=UTF-8"
}
})
.then(function (response) {
// Save the response status in a variable to use later.
fetch_status = response.status;
// Handle success
// eg. Convert the response to JSON and return
return response.json();
})
.then(function (json) {
// Check if the response were success
if (fetch_status == 200) {
// Use the converted JSON
console.log(json);
}
})
.catch(function (error){
// Catch errors
console.log(error);
});
// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/users', {
method: "POST",
// Set the headers
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// Set the post data
body: JSON.stringify({
name : "Jon Doe",
username : "jon-doe",
email : 'jon-doe@unknown.com'
})
})
.then(function (response) {
// Save the response status in a variable to use later.
fetch_status = response.status;
// Handle success
// eg. Convert the response to JSON and return
return response.json();
})
.then(function (json) {
// Check if the response were success
if (fetch_status == 201) {
// Use the converted JSON
console.log(json);
}
})
.catch(function (error){
// Catch errors
console.log(error);
});
In the above snippets, once the fetch()
method’s request is successfully executed on the server, the first then()
method converts the response data info a JavaScript object. Then, in the second then()
method, we can use the object to do whatever we want to do. If there were any errors encountered in the chain, it would pass into the catch()
method.
Today I will share a snippet I've used in a project. Using that function, you…
By default, Bootstrap carousel has no way to add animations to carousel elements. Here I'm…
Laravel comes up with a paginator that generates HTML compatible with the Tailwind CSS framework.…
Bootstrap introduced their icons collection in November 2019 as Bootstrap Icons (v1.0.0-alpha). At that time,…
To create autocomplete feature for input field(s), HTML's datalist tag can be the easiest solution.…
Gulp is a toolkit to automate & enhance our workflow. Most of the time, I…