July 13, 2021

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 than XMLHttpRequest.

✅ 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 of XMLHttpRequest.

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

FeatureAJAX (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

ScenarioSuggestion
Simple API calls, modern appfetch()
Need features like timeout, interceptors, progressaxios
Old browser support (IE) neededXMLHttpRequest (AJAX) or axios
Learning basics✅ Start with fetch()

🧠 One-Sentence Interview Answer

AJAX is the technique, fetch is the modern native API, and axios is a powerful library that makes HTTP requests easier and more feature-rich.”