AJAX (Asynchronous JavaScript and XML) allows you to send and receive data from a server asynchronously, without refreshing the page. Here’s a simple guide on how to send an AJAX request using JavaScript.
Using XMLHttpRequest
Here’s how you can use XMLHttpRequest
to send an AJAX request:
Step-by-Step Example
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it: GET-request for the URL /article/.../load
xhr.open('GET', 'https://api.example.com/data', true);
// Set up a function to handle the response
xhr.onload = function() {
if (xhr.status == 200) { // If the request was successful
console.log('Response:', xhr.responseText); // Log the response
} else {
console.error('Error:', xhr.statusText); // Log the error if any
}
};
// Send the request
xhr.send();
In this example:
- Create a new
XMLHttpRequest
object. - Configure the request using
xhr.open
. - Define a function to handle the response with
xhr.onload
. - Send the request with
xhr.send
.
Using Fetch API
The Fetch API provides a more modern and flexible way to make AJAX requests. Here’s how you can use it:
Step-by-Step Example
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON response
})
.then(data => {
console.log('Data:', data); // Log the data
})
.catch(error => {
console.error('Fetch error:', error); // Log any errors
});
In this example:
- Use
fetch
to make the request. - Check if the response is ok and parse it as JSON.
- Handle the data in the
then
block. - Catch and log any errors with
catch
.
Sending Data with POST Request
To send data to the server, you can use a POST request. Here’s how you can do it with the Fetch API:
fetch('https://api.example.com/data', {
method: 'POST', // Specify the request method
headers: {
'Content-Type': 'application/json' // Specify the content type
},
body: JSON.stringify({ // Convert the data to JSON
key1: 'value1',
key2: 'value2'
})
})
.then(response => response.json()) // Parse the JSON response
.then(data => {
console.log('Data:', data); // Log the data
})
.catch(error => {
console.error('Fetch error:', error); // Log any errors
});
In this example:
- Set the method to
POST
. - Set the headers to specify the content type as JSON.
- Convert the data to JSON format and include it in the
body
.
Conclusion
Sending AJAX requests allows you to interact with a server without refreshing the web page. Whether using XMLHttpRequest
or the modern Fetch API, you can handle asynchronous data operations efficiently. Experiment with these examples to integrate AJAX functionality into your web applications.