Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

AJAX · Show a friendly errorBeginner
function showError(message) {
  const box = document.getElementById('error');
  box.textContent = message;
  box.hidden = false;
}

async function save() {
  try {
    const res = await fetch('/api/save', { method: 'POST' });
    if (!res.ok) throw new Error('bad status');
  } catch (e) {
    showError('We could not save your changes. Please check your connection and try again.');
  }
}

Tell the visitor what happened and what to do, not the technical text.

AJAX · Avoid a cached replyBeginner
fetch('/api/stats', { cache: 'no-store' })
  .then(function (r) { return r.json(); })
  .then(function (stats) { console.log(stats); });

// Or add a changing value to the URL:
fetch('/api/stats?_=' + Date.now());

Ask for fresh data for live numbers.

AJAX · Read JSON sent to PHPBeginner
// api/save.php  (PHP, shown as a comment)
// <?php
// $data = json_decode(file_get_contents('php://input'), true);
// if (!is_array($data) || empty($data['name'])) {
//     http_response_code(422);
//     echo json_encode(['ok' => false, 'error' => 'Name is required']);
//     exit;
// }
// echo json_encode(['ok' => true, 'name' => $data['name']]);

fetch('/api/save.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ali' })
});

PHP does not fill $_POST for JSON bodies. Read php://input yourself.

AJAX · A tiny PHP endpoint for AJAXBeginner
// api/items.php  (this is PHP, shown as a comment)
// <?php
// header('Content-Type: application/json; charset=utf-8');
// $items = [['id' => 1, 'name' => 'Pen'], ['id' => 2, 'name' => 'Book']];
// echo json_encode(['ok' => true, 'items' => $items]);

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

What the other side looks like: PHP that returns JSON.

AJAX · Read response headersBeginner
async function smartRead(url) {
  const res = await fetch(url);
  const type = res.headers.get('content-type') || '';
  return type.indexOf('application/json') !== -1 ? res.json() : res.text();
}

smartRead('/api/items').then(console.log);

Check what the server really sent before you parse it.

AJAX · Send cookies with fetchBeginner
fetch('/api/profile', { credentials: 'same-origin' })   // default: cookies for your own site
  .then(function (r) { return r.json(); });

fetch('/api/private', { credentials: 'omit' });         // never send cookies

Same-origin requests send cookies by default. Set credentials explicitly for other cases.

AJAX · CORS in shortBeginner
// 1) Same site: no CORS needed.
fetch('/api/items');

// 2) Another site: the OTHER server must send  Access-Control-Allow-Origin.
fetch('https://api.example.com/items', { mode: 'cors' });

// 3) Send cookies to another site (server must allow credentials and a fixed origin):
fetch('https://api.example.com/me', { credentials: 'include' });

// PHP on api.example.com:
// header('Access-Control-Allow-Origin: https://www.mysite.com');
// header('Access-Control-Allow-Credentials: true');

A browser only lets your page read a reply from another site if that site allows it. The fix is on the server.

AJAX · Check if a username is freeBeginner
const user = document.getElementById('username');

user.addEventListener('blur', async function () {
  if (!user.value) return;
  const res = await fetch('/api/username-free?name=' + encodeURIComponent(user.value));
  const data = await res.json();
  document.getElementById('hint').textContent = data.ok ? 'Available' : 'Taken';
});

Ask the server when the user leaves the field.

AJAX · Search while typingBeginner
const box = document.getElementById('q');

box.addEventListener('input', async function () {
  const term = box.value.trim();
  if (term.length < 2) return;
  const data = await (await fetch('/api/search?q=' + encodeURIComponent(term))).json();
  document.getElementById('count').textContent = data.items.length + ' results';
});

Send a request on every input event. The next snippets show how to make it smarter.

AJAX · Update with PUTBeginner
async function updateUser(id, data) {
  const res = await fetch('/api/users/' + id, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  if (!res.ok) throw new Error('Update failed');
  return res.json();
}

updateUser(7, { name: 'Ali Khan' });

PUT replaces an item. The id is in the URL, the new data is in the body.

AJAX · Delete with the DELETE methodBeginner
document.addEventListener('click', async function (e) {
  const btn = e.target.closest('.delete');
  if (!btn || !confirm('Delete this item?')) return;

  const res = await fetch('/api/items/' + btn.dataset.id, { method: 'DELETE' });
  if (res.ok) btn.closest('tr').remove();
});

Remove the row from the page only after the server confirmed.

AJAX · Load part of a page into a divBeginner
async function include(selector, url) {
  const box = document.querySelector(selector);
  const res = await fetch(url);
  box.innerHTML = res.ok ? await res.text() : '<p>Could not load content.</p>';
}

include('#sidebar', '/partials/sidebar.html');

Only do this with HTML from your own server.

AJAX · Two linked dropdownsBeginner
const country = document.getElementById('country');
const city = document.getElementById('city');

country.addEventListener('change', async function () {
  city.innerHTML = '<option value="">Loading...</option>';
  const data = await (await fetch('/api/cities?country=' + encodeURIComponent(country.value))).json();
  city.innerHTML = '<option value="">Choose a city</option>';
  data.items.forEach(function (c) { city.add(new Option('City ' + c, c)); });
});

When the first dropdown changes, load the options for the second.

async function fillSelect(id, url) {
  const select = document.getElementById(id);
  const data = await (await fetch(url)).json();
  data.items.forEach(function (value) {
    select.add(new Option('City ' + value, value));
  });
}

fillSelect('city', '/api/cities');

Build option elements from the data.

async function loadDashboard() {
  const [users, orders] = await Promise.all([
    fetch('/api/users').then(function (r) { return r.json(); }),
    fetch('/api/orders').then(function (r) { return r.json(); })
  ]);
  return { users: users.items.length, orders: orders.items.length };
}

loadDashboard().then(console.log);

Start both requests together instead of waiting for the first one to finish.

AJAX · Chain then and catchBeginner
fetch('/api/items')
  .then(function (res) {
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return res.json();
  })
  .then(function (data) {
    return data.items.length;
  })
  .then(function (count) {
    console.log(count + ' items');
  })
  .catch(function (err) {
    console.error(err);
  });

Each then receives the result of the one before. One catch handles all errors.

AJAX · JSON.parse and JSON.stringifyBeginner
const text = '{"name":"Ali","tags":["php","sql"]}';

const obj = JSON.parse(text);
console.log(obj.name, obj.tags.length);

const back = JSON.stringify(obj);
console.log(back);

try {
  JSON.parse('not json');
} catch (e) {
  console.log('Bad JSON:', e.name);
}

JSON is text. parse turns text into an object, stringify does the opposite.

AJAX · POST with XMLHttpRequestBeginner
const x = new XMLHttpRequest();
x.open('POST', '/api/save');
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.onload = function () { console.log(x.responseText); };
x.send('name=' + encodeURIComponent('Ali') + '&age=30');

Send form-style data with the correct header.

AJAX · The old way: XMLHttpRequestBeginner
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/items');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText));
  }
};
xhr.onerror = function () { console.log('Network error'); };
xhr.send();

You will see this in older code. fetch is easier, but the idea is the same.

AJAX · Understand common status codesBeginner
async function request(url) {
  const res = await fetch(url);

  if (res.status === 401) { location.href = '/login'; return; }        // not logged in
  if (res.status === 404) { return { error: 'Not found' }; }           // wrong URL or deleted
  if (res.status === 422) { return { error: 'Please check the form' }; } // validation failed
  if (res.status >= 500)  { return { error: 'Server problem' }; }      // not your fault

  return res.json();
}

React differently to the main status codes.

AJAX · Read plain text or HTMLBeginner
fetch('/partials/news.html')
  .then(function (r) { return r.text(); })
  .then(function (html) { document.getElementById('news').innerHTML = html; });

Use response.text() when the server sends text instead of JSON.

AJAX · Send a form with FormDataBeginner
const form = document.getElementById('contact');

form.addEventListener('submit', function (e) {
  e.preventDefault();
  fetch('/api/contact', { method: 'POST', body: new FormData(form) })
    .then(function (r) { return r.json(); })
    .then(function () { form.reset(); });
});

FormData reads every field of the form, including files. Do not set Content-Type yourself.

AJAX · Send JSON with POSTBeginner
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ali', city: 'Lahore' })
})
  .then(function (r) { return r.json(); })
  .then(function (data) { console.log('Saved', data); });

Set the Content-Type header and turn the object into text with JSON.stringify.

AJAX · Send values in the URLBeginner
const params = new URLSearchParams({ q: 'php & sql', page: 2 });

fetch('/api/search?' + params.toString())
  .then(function (r) { return r.json(); })
  .then(console.log);

URLSearchParams encodes spaces and special characters for you.

AJAX · Show a loading messageBeginner
async function loadWithSpinner() {
  const spinner = document.getElementById('spinner');
  spinner.hidden = false;
  try {
    const res = await fetch('/api/items');
    return await res.json();
  } finally {
    spinner.hidden = true;
  }
}

loadWithSpinner();

Show it before the request and hide it in finally, so it hides even on errors.

const btn = document.getElementById('load');

btn.addEventListener('click', async function () {
  btn.disabled = true;
  btn.textContent = 'Loading...';
  try {
    const data = await (await fetch('/api/items')).json();
    document.getElementById('out').textContent = data.items.length + ' items loaded';
  } finally {
    btn.disabled = false;
    btn.textContent = 'Load';
  }
});

Run the request from an event listener and disable the button while it works.

AJAX · Show the result in the pageBeginner
async function showItems() {
  const data = await (await fetch('/api/items')).json();
  const list = document.getElementById('list');
  list.innerHTML = '';
  data.items.forEach(function (item) {
    const li = document.createElement('li');
    li.textContent = 'Item ' + item;
    list.appendChild(li);
  });
}

showItems();

Create elements and use textContent, so data can never run as HTML.

async function load() {
  try {
    const response = await fetch('/api/items');
    if (!response.ok) throw new Error('HTTP ' + response.status);
    return await response.json();
  } catch (err) {
    console.error('Could not load:', err.message);
    return null;
  }
}

load();

Network failures and bad status codes both end up in catch.

AJAX · Check response.okBeginner
async function getJSON(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('Request failed with status ' + response.status);
  }
  return response.json();
}

getJSON('/api/items').then(console.log).catch(function (err) { console.error(err.message); });

fetch does not fail on 404 or 500. Always check response.ok yourself.

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.