In JavaScript if you want to make an AJAX request then you can either use XMLHttpRequest
object or you can use modern fetch
API. Here I have provided examples of both the ways :
1. Using XMLHttpRequest
JavaScript
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it: GET-request for the URL /data
xhr.open('GET', '/data', true);
// Send the request
xhr.send();
// This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) {
// handle the error
console.error('Error:', xhr.status, xhr.statusText);
} else {
// handle the successful response
console.log('Response:', xhr.responseText);
}
};
2. Using Fetch API (Modern Approach)
JavaScript
// Make a GET request using fetch
fetch('/data')
.then(function(response) {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON or text
return response.json(); // or response.text() for non-JSON data
})
.then(function(data) {
// Handle the data
console.log('Data:', data);
})
.catch(function(error) {
// Handle any errors that occurred during the fetch
console.error('Fetch Error:', error);
});
3. Using Fetch API with Async/Await (Modern Approach)
JavaScript
async function fetchData() {
try {
// Make a GET request using fetch
const response = await fetch('/data');
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON or text
const data = await response.json(); // or response.text() for non-JSON data
// Handle the data
console.log('Data:', data);
} catch (error) {
// Handle any errors that occurred during the fetch
console.error('Fetch Error:', error);
}
}
// Call the function
fetchData();