Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

JavaScript AJAX and Fetch API

Lesson 24 of 34 in the free Web Technologies notes on Siksha Sarovar, written by Rohit Jangra.

JavaScript AJAX and Fetch API

What is AJAX?

AJAX (Asynchronous JavaScript and XML) allows web pages to communicate with a server and update content without reloading the page.

Modern AJAX uses JSON instead of XML, and the Fetch API instead of the old XMLHttpRequest.

The Fetch API

// Basic GET request
fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error: " + response.status);
        }
        return response.json(); // parse JSON body
    })
    .then(data => {
        console.log(data.title);
    })
    .catch(error => {
        console.error("Fetch failed:", error);
    });

Async/Await with Fetch

async function getPost(id) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        if (!response.ok) throw new Error(`Error: ${response.status}`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Failed to fetch post:", error);
    }
}

// POST request
async function createPost(postData) {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(postData)
    });
    const data = await response.json();
    console.log("Created:", data);
}

createPost({ title: "New Post", body: "Content here", userId: 1 });

Fetch Options

const options = {
    method: "PUT",           // GET | POST | PUT | PATCH | DELETE
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer TOKEN"
    },
    body: JSON.stringify({ name: "Alice" }),
    mode: "cors",           // cors | no-cors | same-origin
    credentials: "include"  // include cookies
};

Old XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        console.log(data);
    }
};
xhr.send();

Promises Explained

// A Promise has 3 states: pending, fulfilled, rejected
const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Done!"), 1000);
});

promise
    .then(result => console.log(result))  // "Done!"
    .catch(err => console.error(err))
    .finally(() => console.log("Finished"));

// Promise.all — run multiple in parallel
const [users, posts] = await Promise.all([
    fetch("/api/users").then(r => r.json()),
    fetch("/api/posts").then(r => r.json())
]);

Fetch vs XMLHttpRequest

FeatureFetchXHR
SyntaxPromise-basedCallback-based
ReadabilityCleanVerbose
StreamingYesNo
Progress eventsLimitedYes
Key Takeaway: Use the Fetch API with async/await for clean asynchronous HTTP requests. Always handle errors with try/catch and check response.ok before processing data.