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
| Feature | Fetch | XHR |
|---|---|---|
| Syntax | Promise-based | Callback-based |
| Readability | Clean | Verbose |
| Streaming | Yes | No |
| Progress events | Limited | Yes |
Key Takeaway: Use the Fetch API withasync/awaitfor clean asynchronous HTTP requests. Always handle errors withtry/catchand checkresponse.okbefore processing data.