Differences Between Fetch API and AJAX

FeatureFetch APIAJAX/XHR
SyntaxCleaner and promise-basedCallback-heavy and verbose
Error HandlingEasier with .catch()Requires manually handling errors
Modern UsageStandard in modern JavaScriptLegacy technique
Data FormatsSupports JSON, blobs, and streamsMostly JSON and XML
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();

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));
  • 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.