JavaScript AJAX - Exercise 1

AJAX lets a page request data from a server without a full page reload.

javascript

fetch('/api/users').then(response => response.json());

GET is used when the client wants to read data from a server.

javascript

fetch('/api/products');

It returns a promise that resolves to the parsed JSON value.

javascript

fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data));

Use response.ok, which is true for successful HTTP status codes.

javascript

fetch('/api/data').then(response => {
  if (!response.ok) throw new Error('Request failed');
});

POST commonly sends new data in the request body.

javascript

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.

javascript

const headers = { 'Content-Type': 'application/json' };

It represents a failure such as a network error or a thrown error.

javascript

fetch('/api/data')
  .catch(error => console.error(error));

Set a loading state before the request and clear it after completion.

javascript

loading.textContent = 'Loading...';
fetch('/api/data').finally(() => {
  loading.textContent = '';
});

It keeps the page responsive while the browser waits for the server.

javascript

async function loadUsers() {
  const response = await fetch('/api/users');
  return response.json();
}

Catch the error and show a clear, actionable message.

javascript

try {
  await fetch('/api/data');
} catch (error) {
  message.textContent = 'Could not load data.';
}