About Lesson
Differences Between Fetch API and AJAX
Feature | Fetch API | AJAX/XHR |
---|---|---|
Syntax | Cleaner and promise-based | Callback-heavy and verbose |
Error Handling | Easier with .catch() | Requires manually handling errors |
Modern Usage | Standard in modern JavaScript | Legacy technique |
Data Formats | Supports JSON, blobs, and streams | Mostly JSON and XML |
Using AJAX (XHR): Basic Example of AJAX
JavaScript
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error("Error: ", xhr.statusText);
}
};
xhr.onerror = function() {
console.error("Request failed");
};
xhr.send();
Using Fetch API: Basic Fetch Example
Here’s the complete code for the third method, which logs each item in a structured, readable format:
JavaScript
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Logs each item's details in a formatted way
data.forEach(item => {
console.log("Post Details:");
console.log(`- ID: ${item.id}`);
console.log(`- Title: ${item.title}`);
console.log(`- Body: ${item.body}`);
console.log("---------------------");
});
})
.catch(error => console.error("Fetch error:", error));
Key Takeaways:
- AJAX laid the groundwork for asynchronous HTTP requests but is now considered legacy.
- Fetch API is the modern and more intuitive approach to handle HTTP requests.
- Both are integral to creating dynamic, interactive web applications.