AJAX (Asynchronous JavaScript and XML) is a technique that allows a web page to communicate with a server without reloading the entire page. Although the name mentions XML, modern applications usually exchange data in JSON format.
With AJAX, you can update parts of a web page (like a table, list, or message area) after sending background HTTP requests using JavaScript.
XMLHttpRequest or the
modern fetch() API.GET (read data) and
POST (send data).
XMLHttpRequest to
track request progress and result./users,
/posts, etc.
fetch() API returns a Promise, enabling
clean async handling with .then() or async/await.In a typical AJAX operation, the flow looks like this:
XMLHttpRequest) or call fetch().Using the older but still supported XMLHttpRequest object:
// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
// Handle state changes and check for a successful response
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Parse the JSON response from the server
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
// Send the request to the server
xhr.send();
The fetch() API returns a Promise and provides a cleaner syntax:
// Send a GET request using fetch()
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Handle the parsed JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the request
console.error('Error:', error);
});
To send JSON data, set the HTTP method and appropriate headers:
// Create a new XMLHttpRequest for a POST request
let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
// Handle the response from the server
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
};
// Prepare the JSON body to send to the server
const body = {
name: 'John',
age: 30
};
// Send the JSON data as a string
xhr.send(JSON.stringify(body));
The same POST request written using fetch():
// Send a POST request with JSON data using fetch()
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John',
age: 30
})
})
.then(response => response.json())
.then(data => {
// Log the server's JSON response
console.log('Server response:', data);
})
.catch(error => {
// Handle any errors from the request
console.error('Error:', error);
});
Click the button below to send an AJAX request (using fetch()) to a public test
API.
The JSON response will be shown in the box.
Click "Load Sample Data" to see the response here.
In this demo:
fetch() GET request.<pre> block.fetch() for modern projects; it has a simpler Promise-based API..catch() (for fetch()) or
onreadystatechange checks (for XMLHttpRequest).
fetch() and
XMLHttpRequest with true).
XMLHttpRequest to send a POST request with JSON data and
log the server response in the console.
XMLHttpRequest calls using the
Fetch API with Promises.