JavaScript Fetch & AJAX
AJAX (Asynchronous JavaScript and XML) lets a web page fetch data from a server without reloading. The modern `fetch()` API is the standard tool for making these network requests.
`fetch(url)` returns a Promise that resolves to a Response object; you typically call `.json()` on it to parse the body, often combined with async/await for readability.
Basic fetch usage
`fetch('https://api.example.com/data').then(res => res.json()).then(data => console.log(data))` retrieves and parses JSON data from an API.
fetch with async/await
`const res = await fetch(url); const data = await res.json();` reads more linearly and pairs well with try/catch for error handling.
fetch("https://api.example.com/users/1")
.then(res => res.json())
.then(data => console.log(data.name));(depends on API response)fetch retrieves data, then .json() parses the response body.
async function getUser() {
try {
const res = await fetch("https://api.example.com/users/1");
const data = await res.json();
console.log(data.name);
} catch (err) {
console.log("Request failed:", err.message);
}
}(depends on API response)async/await version with error handling via try/catch.
Key points
- fetch() sends an HTTP request and returns a Promise.
- res.json() parses the response body as JSON, returning another Promise.
- fetch pairs naturally with async/await for readable code.
- Always handle errors โ fetch only rejects on network failure, not HTTP error status codes.
