JavaScript AJAX - Exercise 1
AJAX lets a page request data from a server without a full page reload.
fetch('/api/users').then(response => response.json());
GET is used when the client wants to read data from a server.
fetch('/api/products');
It returns a promise that resolves to the parsed JSON value.
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
Use response.ok, which is true for successful HTTP status codes.
fetch('/api/data').then(response => {
if (!response.ok) throw new Error('Request failed');
});
POST commonly sends new data in the request body.
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ava' })
});
It tells the server that the request body contains JSON.
const headers = { 'Content-Type': 'application/json' };
It represents a failure such as a network error or a thrown error.
fetch('/api/data')
.catch(error => console.error(error));
Set a loading state before the request and clear it after completion.
loading.textContent = 'Loading...';
fetch('/api/data').finally(() => {
loading.textContent = '';
});
It keeps the page responsive while the browser waits for the server.
async function loadUsers() {
const response = await fetch('/api/users');
return response.json();
}
Catch the error and show a clear, actionable message.
try {
await fetch('/api/data');
} catch (error) {
message.textContent = 'Could not load data.';
}