XMLHttpRequest vs Fetch API in JavaScript – Complete Guide
In modern web development, websites frequently communicate with servers without reloading the page. This process is called AJAX (Asynchronous JavaScript and XML).
Two major ways to make HTTP requests in JavaScript are:
- XMLHttpRequest (XHR) – Traditional method
- Fetch API – Modern promise-based method
Both allow a web application to send and receive data from servers asynchronously.
1. What is XMLHttpRequest?
XMLHttpRequest (XHR) is a JavaScript object used to interact with servers. It allows web pages to request data from a server without refreshing the page.
It was introduced before modern JavaScript promises and is widely used in older applications.
Using XHR, you can:
- Send HTTP requests (GET, POST, PUT, DELETE)
- Fetch JSON or XML data
- Upload files
- Monitor request progress
Real Life Example
When you search something on Google and results appear instantly without refreshing the page, the browser is using AJAX requests internally.
How XMLHttpRequest Works
The process usually follows these steps:
- Create XMLHttpRequest object
- Open connection to server
- Send request
- Receive response
- Process the response
Example: GET Request using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
Explanation
| Line | Description |
|---|---|
new XMLHttpRequest() |
Creates request object |
open() |
Specifies request type and URL |
onload |
Executes when response arrives |
responseText |
Contains response data |
send() |
Sends the request |
Example: POST Request using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
console.log(xhr.responseText);
};
var data = JSON.stringify({
title: "OnlineLearner",
body: "Learn JavaScript",
userId: 1
});
xhr.send(data);
This sends data from the browser to the server.
Problems with XMLHttpRequest
Although powerful, XHR has several drawbacks:
1. Callback-based
It relies heavily on callbacks which can create callback hell.
2. Hard to Read
The syntax becomes complex for large applications.
3. No Native Promise Support
Developers had to use external libraries.
Because of these problems, the Fetch API was introduced.
2. What is Fetch API?
The Fetch API is a modern JavaScript interface used to make HTTP requests.
It is promise-based, making it easier to write asynchronous code.
Fetch is now supported by all modern browsers.
Key features:
- Uses Promises
- Cleaner syntax
- Supports async/await
- Handles JSON easily
Example: GET Request using Fetch
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
Explanation
| Part | Description |
|---|---|
fetch() |
Sends request to server |
response.json() |
Converts response into JSON |
.then() |
Handles successful response |
.catch() |
Handles errors |
Example using Async/Await (Modern Approach)
async function getData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
This is the most common method used in modern applications.
Example: POST Request using Fetch
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "OnlineLearner",
body: "Learn Fetch API",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
XMLHttpRequest vs Fetch API
| Feature | XMLHttpRequest | Fetch API |
|---|---|---|
| Syntax | Complex | Simple |
| Promises | Not supported | Supported |
| Async/Await | No | Yes |
| Error Handling | Difficult | Easy |
| Modern Support | Older method | Modern standard |
| Readability | Harder | Cleaner |
When Should You Use XMLHttpRequest?
Use XHR when:
- Working with legacy applications
- Supporting very old browsers
- Handling progress events (file uploads)
When Should You Use Fetch?
Use Fetch when:
- Building modern web applications
- Using async/await
- Working with REST APIs
Fetch is now the recommended approach.
Real-World Scenario
Suppose you are building a Laravel + JavaScript application like your website onlinelearner.in.
Example uses:
| Feature | Request Type |
|---|---|
| Load blog posts | GET |
| Submit comment | POST |
| Update profile | PUT |
| Delete comment | DELETE |
These API calls are usually handled using Fetch API.
Best Practice
Modern applications usually combine:
- Fetch API
- Async/Await
- JSON APIs
Example structure:
async function fetchUsers() {
const response = await fetch('/api/users');
const users = await response.json();
return users;
}
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
