Introduction to JavaScript AJAX and XMLHttpRequest


JavaScript AJAX (Asynchronous JavaScript and XML) is a technique used to exchange data with a server without requiring the entire page to be refreshed. This allows for dynamic and asynchronous communication between the client and server. In this guide, we'll introduce JavaScript AJAX and the XMLHttpRequest object, and provide sample code to demonstrate its usage.


XMLHttpRequest Object


The XMLHttpRequest object is the foundation of AJAX in JavaScript. It allows you to make HTTP requests to fetch or send data to a server without reloading the entire page. Here's a basic example of how to create an XMLHttpRequest object:


const xhr = new XMLHttpRequest();

Making a GET Request


Let's make a simple GET request to retrieve data from a server and update the page. Here's an example:


const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onload = function() {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log('Data:', responseData);
}
};
xhr.send();

Making a POST Request


You can also make POST requests to send data to the server. Here's a sample code for a POST request:


const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.setRequestHeader('Content-Type', 'application/json');
const postData = JSON.stringify({
title: 'New Post',
body: 'This is the post body.',
userId: 1
});
xhr.onload = function() {
if (xhr.status === 201) {
const responseData = JSON.parse(xhr.responseText);
console.log('Created Post:', responseData);
}
};
xhr.send(postData);

Handling Errors


It's essential to handle errors when working with XMLHttpRequest. You can do this by adding error-handling logic to the request:


const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/invalid-url', true);
xhr.onload = function() {
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log('Data:', responseData);
} else {
console.error('Request failed with status:', xhr.status);
}
};
xhr.onerror = function() {
console.error('Request error occurred.');
};
xhr.send();

Conclusion


JavaScript AJAX and the XMLHttpRequest object are fundamental tools for building interactive and dynamic web applications. They allow you to fetch and send data to and from servers without page reloads, providing a seamless user experience.


Explore JavaScript AJAX further to build interactive web applications with real-time data exchange between the client and server.