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:
- XMLHttpRequest
- Fetch API
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 modernFetch 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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.