Handling AJAX Calls with Fetch API Instead of $.ajax()
Introduction
AJAX (Asynchronous JavaScript and XML) is a crucial technique for updating web pages without reloading. Traditionally, developers have used $.ajax()
from jQuery for AJAX requests, but modern JavaScript provides the Fetch API, a more powerful and flexible alternative.
In this guide, we’ll cover everything about handling AJAX calls using the Fetch API instead of $.ajax()
, from basics to advanced use cases. By the end, you’ll have a deep understanding of how Fetch API works, its advantages over $.ajax()
, and how to transition from jQuery-based AJAX calls to Fetch API efficiently.
1. Understanding AJAX and jQuery’s $.ajax()
What is AJAX?
AJAX allows web pages to fetch or send data asynchronously without refreshing. This improves the user experience by allowing real-time updates without a full-page reload.
How $.ajax()
Works in jQuery
Traditionally, developers used jQuery’s $.ajax()
function for making asynchronous requests. Here’s an example:
$.ajax({
url: "https://api.example.com/data",
type: "GET",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
While $.ajax()
is convenient, it comes with some drawbacks:
- Requires jQuery, adding extra dependencies.
- Uses callback-based syntax, which is harder to maintain than modern async/await.
- Less flexible than native JavaScript’s Fetch API.
2. What is Fetch API?
The Fetch API is a modern JavaScript feature for making HTTP requests. It provides a promise-based approach for fetching resources asynchronously.
Basic Fetch API Syntax
Here’s a simple example of fetching data from an API:
fetch("https://api.example.com/data")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Handle the data
.catch(error => console.error("Error:", error)); // Handle errors
3. Advantages of Using Fetch API over $.ajax()
Feature | Fetch API | $.ajax() |
---|---|---|
Native to JavaScript | ✅ Yes | ❌ Requires jQuery |
Promise-Based | ✅ Yes | ❌ Uses callbacks |
Supports Async/Await | ✅ Yes | ❌ No native support |
Streaming Responses | ✅ Yes | ❌ No |
Better Error Handling | ✅ Yes | ❌ Harder to manage |
Because Fetch API is built into modern browsers, it eliminates jQuery as a dependency and allows writing cleaner, modern JavaScript.
4. Performing Basic AJAX Calls with Fetch API
GET Request with Fetch
Equivalent of $.ajax({ type: "GET" })
:
fetch("https://api.example.com/data")
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Handle data
.catch(error => console.error("Fetch Error:", error));
Using Async/Await for Cleaner Code
With async/await, the same GET request looks cleaner:
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch Error:", error);
}
}
fetchData();
5. Making a POST Request with Fetch API
Equivalent of $.ajax({ type: "POST" })
:
fetch("https://api.example.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "John", age: 30 })
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Fetch Error:", error));
Using Async/Await for Cleaner POST Requests
async function postData() {
try {
let response = await fetch("https://api.example.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "John", age: 30 })
});
let data = await response.json();
console.log("Success:", data);
} catch (error) {
console.error("Fetch Error:", error);
}
}
postData();
6. Handling HTTP Response Status in Fetch API
Unlike $.ajax()
, Fetch API does not reject a promise for HTTP errors (like 404 or 500). You must handle them manually:
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
if (!response.ok) { // Check if the response status is not OK (200-299)
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch Error:", error);
}
}
fetchData();
7. Sending Form Data with Fetch API
If you’re sending form data, you can use FormData
instead of JSON:
let formData = new FormData();
formData.append("username", "john_doe");
formData.append("password", "secure123");
fetch("https://api.example.com/login", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(data => console.log("Login Successful:", data))
.catch(error => console.error("Fetch Error:", error));
8. Handling Timeouts in Fetch API
Unlike $.ajax()
, Fetch API doesn’t have built-in timeout handling. You need to use AbortController
:
async function fetchDataWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), timeout);
try {
let response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log(data);
} catch (error) {
if (error.name === "AbortError") {
console.error("Fetch request timed out");
} else {
console.error("Fetch Error:", error);
}
}
}
fetchDataWithTimeout("https://api.example.com/data");
9. Making Multiple AJAX Calls with Fetch API
You can use Promise.all()
to fetch multiple resources concurrently:
Promise.all([
fetch("https://api.example.com/users").then(res => res.json()),
fetch("https://api.example.com/posts").then(res => res.json())
])
.then(([users, posts]) => {
console.log("Users:", users);
console.log("Posts:", posts);
})
.catch(error => console.error("Fetch Error:", error));
10. Fetch API vs. Axios: Which One Should You Use?
If you’re looking for better error handling and response transformations, consider using Axios:
axios.get("https://api.example.com/data")
.then(response => console.log(response.data))
.catch(error => console.error("Axios Error:", error));
Axios is more user-friendly, but Fetch API is native and lightweight.
Switching from $.ajax()
to Fetch API is a modern and efficient way to handle AJAX requests. The Fetch API is:
✅ Native to JavaScript (no jQuery required)
✅ Uses Promises for cleaner syntax
✅ More flexible and lightweight
By learning Fetch API, you future-proof your JavaScript skills while keeping your code cleaner and faster!