AJAX and Fetch API in JavaScript —
Imagine you are the owner of a busy restaurant called JavaScript Restaurant. 🍽️
Customers come to your restaurant and ask for different things. One customer wants the menu, another wants the price list, and someone else wants to know whether a dish is available.
You could close the entire restaurant, collect all the information, and then open it again. But that would waste everyone’s time!
Instead, you send a waiter to the kitchen to collect the requested information while the restaurant continues serving other customers.
This is the basic idea behind AJAX and the Fetch API in JavaScript.
1. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
Imagine a customer clicks a button to see the latest menu. The waiter goes to the kitchen, collects the menu, and brings it back without stopping the restaurant’s other activities.
Similarly, AJAX allows a web page to communicate with a server and update information without reloading the entire page.
For example:
- Loading new messages in a chat application.
- Showing search suggestions while typing.
- Updating information on a webpage.
- Retrieving product details from a server.
AJAX is not a programming language. It is a technique for exchanging data between a browser and a server asynchronously.
Although AJAX originally included XML in its name, modern applications commonly exchange JSON data.
2. What is the Fetch API?
Now imagine the restaurant hires a new waiter who uses a modern digital ordering system.
This waiter can request information from the kitchen, wait for the response, and bring the result back efficiently.
In JavaScript, the Fetch API is a modern way to make HTTP requests to servers.
Let’s see an example:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log("Error:", error);
});Story explanation
Imagine the waiter follows four steps:
fetch()sends a request to the server.response.json()reads the response body and converts JSON into a JavaScript value..then(data => ...)receives the converted data..catch()handles errors that reject the promise, such as certain network failures.
The server might return information about a user, such as a name, email address, and username.
The important point is that the browser can continue doing other work while the request is in progress.
3. How AJAX and Fetch Work Together
Imagine a customer wants to check the weather on a webpage.
Here is the journey:
Step 1: The customer clicks the weather button.
Step 2: JavaScript sends a request to a server using fetch().
Step 3: The server processes the request and sends back data.
Step 4: JavaScript reads the response.
Get Raveenanagar’s stories in your inbox
Join Medium for free to get updates from this writer.
Step 5: The webpage displays the weather information without a full page reload.
This is an example of using the Fetch API to perform AJAX.
4. Fetch API with async and await
Our restaurant waiter now has a simpler instruction system. Instead of writing multiple .then() callbacks, the waiter can use async and await to make the code easier to read.
async function getUser() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);if (!response.ok) {
throw new Error("Failed to fetch user");
} const data = await response.json(); console.log(data);
} catch (error) {
console.log("Error:", error.message);
}
}getUser();
What happens in this story?
asyncallows the function to useawait.await fetch()waits for the server response without blocking the browser's main thread.response.okchecks whether the HTTP status indicates success.await response.json()reads and converts the response body.try...catchhandles errors.
Notice that fetch() does not automatically reject its promise for HTTP errors such as 404 Not Found. That's why checking response.ok is important.
5. AJAX vs. Fetch API
AJAX
Fetch API
A technique for asynchronous server communication
A JavaScript API for making HTTP requests
Can use XMLHttpRequest
Uses promises
Can be implemented in different ways
Provides a modern request interface
Can exchange JSON, XML, text, and other data
Can handle JSON, text, and other response formats
Remember: AJAX and Fetch are not competitors. Fetch is one way to implement AJAX.
6. A Real-Life Example
Imagine an online shopping website.
When you click “Show Product Details,” JavaScript can request product information from a server. The server returns the data, and the webpage displays the product name, description, and price without reloading the entire page.
This makes the website feel faster and more interactive.
Conclusion
AJAX is the overall technique of communicating with a server asynchronously, while the Fetch API is a modern JavaScript tool for sending requests and receiving responses.
Think of it this way:
- AJAX is the restaurant’s way of serving new information without closing the restaurant.
- Fetch API is the modern waiter who carries requests and responses between the customer and the kitchen.
Together, they help developers build dynamic websites, interactive applications, chat systems, search features, and much more.






