What is AJAX XMLHttpRequest Fetch?
AJAX (Asynchronous JavaScript and XML) is a technique used to send and receive data asynchronously from a server without reloading the web page. Two popular methods to perform AJAX requests are:
Both allow you to make HTTP requests (GET, POST, etc.) and handle the server response dynamically.
Difference Between XMLHttpRequest and Fetch
| Feature |
XMLHttpRequest |
Fetch API |
| Syntax |
Verbose and older |
Modern and cleaner |
| Promises support |
No (uses event listeners) |
Yes (based on Promises) |
| Browser support |
Very wide (older browsers too) |
Modern browsers only |
| Error handling |
Manual |
Built-in with .catch() |
AJAX XMLHttpRequest Example (GET)
<!DOCTYPE html>
<html>
<head>
<title>AJAX XMLHttpRequest Fetch Example</title>
</head>
<body>
<h2>AJAX using XMLHttpRequest</h2>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>
<script>
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
}
};
xhr.send();
}
</script>
</body>
</html>
AJAX Fetch Example (GET)
<!DOCTYPE html>
<html>
<head>
<title>AJAX XMLHttpRequest Fetch Example</title>
</head>
<body>
<h2>AJAX using Fetch API</h2>
<button onclick="fetchData()">Fetch Data</button>
<div id="result"></div>
<script>
function fetchData() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
document.getElementById("result").innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
Conclusion on AJAX XMLHttpRequest Fetch
- AJAX XMLHttpRequest Fetch refers to the combined concept of making asynchronous requests using either
XMLHttpRequest or the modern Fetch API.
- Use XMLHttpRequest for older browser support.
- Prefer Fetch API for cleaner and modern code.
- Both are essential in front-end development for dynamic user experiences.