AJAX and Fetch API
AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages. It allows you to send and receive data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
While the name includes "XML", JSON is now the more common data format used with AJAX.
XMLHttpRequest
The original way to do AJAX was with the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
While still supported, XMLHttpRequest can be verbose and less intuitive than the more modern Fetch API.
Fetch API
The Fetch API is a modern, promise-based API for making network requests. It is simpler and more powerful than XMLHttpRequest.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
Making a POST Request with Fetch
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));