Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

AJAX · fetch with async and awaitBeginner
async function loadItems() {
  const response = await fetch('/api/items');
  const data = await response.json();
  return data.items;
}

loadItems().then(function (items) { console.log(items.length + ' items'); });

The same request written in a readable top-to-bottom style.

fetch('/api/items')
  .then(function (response) { return response.json(); })
  .then(function (data) { console.log(data); });

AJAX asks the server for data without reloading the page. fetch returns a promise.

AJAX · Load JSON with fetch()Beginner
async function loadUsers() {
  try {
    const res = await fetch('api/users.php');
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const users = await res.json();
    console.log(users);
  } catch (err) {
    console.error('Could not load users:', err);
  }
}
loadUsers();

The modern way to do AJAX. Check response.ok before using the data.