To make an AJAX (Asynchronous JavaScript and XML) call from JavaScript, you can use the XMLHttpRequest
object or the more modern fetch
API. Here’s how you can do both:
1. Using XMLHttpRequest
(older method):
// Create a new instance of XMLHttpRequest
var xhr = new XMLHttpRequest();
// Configure the request (GET or POST, URL, asynchronous)
xhr.open('GET', 'https://api.example.com/data', true);
// Set up a function to handle the response when it's ready
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Parse the response JSON (if it's JSON data)
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// Send the request
xhr.send();
2. Using the fetch
API (modern approach):
// Use the fetch API to make a GET request
fetch('https://api.example.com/data')
.then(response => {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON data
})
.then(data => {
console.log(data); // Handle the parsed data
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
Key differences:
XMLHttpRequest
: An older method that’s more complex and callback-based.fetch
: More modern, returns Promises, and is generally simpler to work with for handling asynchronous requests.
Let me know if you need a specific example or further explanation!