Ajax (Asynchronous JavaScript and XML) is a technique for making asynchronous HTTP requests from the browser. It allows you to update parts of a web page without refreshing the entire page.
The XMLHttpRequest object is a core component of making Ajax requests in JavaScript.
// Using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
// Request was successful
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
// Error occurred
console.error('Error:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('Error:', xhr.statusText);
};
xhr.send();
You can use Ajax to make GET requests to retrieve data from a server.
// Making a GET request using Fetch API
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST requests are used to send data to a server, often used for form submissions or sending JSON data.
// Making a POST request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: 1,
title: 'New Post',
body: 'This is the body of the new post.'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
The Fetch API is a modern replacement for XMLHttpRequest, providing a simpler, more powerful way to make HTTP requests.
// Using the Fetch API
fetch('https://jsonplaceholder.typicode.com/todos/1')
.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('Error:', error);
});
Once a request is made, you'll need to handle the response from the server.
// Handling a response from a server
fetch('https://jsonplaceholder.typicode.com/todos/1')
.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('Error:', error));
Ajax supports various HTTP methods for different types of requests. These include GET, POST, PUT, DELETE, and more.
// Making a PUT request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
title: 'Updated Post Title',
body: 'Updated body content.'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Making a DELETE request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log('Deleted:', data))
.catch(error => console.error('Error:', error));
Headers provide additional information about the request or response. You can set custom headers when making Ajax requests.
// Setting custom headers in a Fetch API request
fetch('https://jsonplaceholder.typicode.com/todos/1', {
headers: {
'Custom-Header': 'MyCustomValue'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Ajax is a crucial technique for creating dynamic, interactive web applications. With JavaScript, you can make asynchronous requests to servers, fetch data, and update your web page dynamically. Understanding how to use XMLHttpRequest and the Fetch API, along with handling responses, HTTP methods, and headers, will greatly enhance your web development capabilities.