AJAX (Asynchronous JavaScript and XML) and the Fetch API are powerful tools in web development for making asynchronous requests to servers, retrieving data, and updating the DOM without the need for a page refresh. Here's an introduction to AJAX and the Fetch API:
AJAX (Asynchronous JavaScript and XML):
AJAX allows you to send and receive data from a server asynchronously without reloading the entire page. It can be used to fetch data, send data, and update parts of a webpage.
Creating an XMLHttpRequest Object:
let xhr = new XMLHttpRequest();
Making a GET Request:
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let responseData = JSON.parse(xhr.responseText);
console.log(responseData);
} else {
console.error('Error:', xhr.status);
}
}
};
xhr.send();
Fetch API:
The Fetch API is a modern replacement for XMLHttpRequest that provides a simpler and more powerful way to make network requests.