AJAX vs fetch vs axios — Simple Comparison
✅ What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It’s a technique (not a function or library) to send HTTP requests without reloading the page.
✅ Example: Using XMLHttpRequest
(old-style AJAX)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
🟡 Used before fetch
or axios
. Verbose and harder to use.
✅ What is fetch
?
fetch()
is a modern built-in JavaScript API to make HTTP requests.
It’s based on Promises, simpler thanXMLHttpRequest
.
✅ Example:
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
🟢 Clean and modern, but lacks some advanced features.
✅ What is axios
?
axios
is a popular third-party library built on top ofXMLHttpRequest
.
It simplifies syntax and supports:
- Interceptors
- Request/response transformation
- Automatic JSON parsing
- Cancel tokens, etc.
✅ Example:
axios.get('https://api.example.com/data')
.then(res => console.log(res.data))
.catch(err => console.error(err));
🟢 Shorter code than fetch
, better browser support and extra features.
⚖️ Comparison Table
Feature | AJAX (XMLHttpRequest) | fetch() | axios |
---|---|---|---|
Built-in | ✅ Yes | ✅ Yes | ❌ No (need to install) |
Based on Promises | ❌ No (callback-based) | ✅ Yes | ✅ Yes |
Browser support | ✅ Very old browsers | ❌ IE not supported | ✅ Supports IE 11+ |
Simplicity | ❌ Complex | ✅ Simple | ✅ Very simple |
JSON auto parse | ❌ Manual | ❌ Need .json() | ✅ Built-in |
Request cancel | ❌ Hard | ❌ Manual workaround | ✅ Easy with cancel tokens |
Interceptors | ❌ No | ❌ No | ✅ Yes |
File upload support | ✅ Yes | ✅ Yes | ✅ Yes |
✅ When to Use
Scenario | Suggestion |
---|---|
Simple API calls, modern app | ✅ fetch() |
Need features like timeout, interceptors, progress | ✅ axios |
Old browser support (IE) needed | ✅ XMLHttpRequest (AJAX) or axios |
Learning basics | ✅ Start with fetch() |
🧠 One-Sentence Interview Answer
“
AJAX
is the technique,fetch
is the modern native API, andaxios
is a powerful library that makes HTTP requests easier and more feature-rich.”
Comments are closed.