Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
// HTML: <meta name="csrf" content="<?= htmlspecialchars($_SESSION['csrf']) ?>">
const token = document.querySelector('meta[name="csrf"]').content;
async function postJson(url, data) {
const res = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}
// PHP side: hash_equals($_SESSION['csrf'], $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')Put the token in a meta tag and send it as a header on every POST. The server must compare it with the one stored in the session.
async function loggedFetch(url, options = {}) {
const started = performance.now();
const method = options.method || 'GET';
try {
const res = await fetch(url, options);
console.log(method, url, res.status, Math.round(performance.now() - started) + ' ms');
return res;
} catch (e) {
console.warn(method, url, 'FAILED', e.message);
throw e;
}
}A small wrapper that logs each request and how long it took. Handy while developing.
function renderTable(rows, columns) {
const table = document.createElement('table');
const head = table.createTHead().insertRow();
columns.forEach(c => head.appendChild(Object.assign(document.createElement('th'), { textContent: c })));
const body = table.createTBody();
rows.forEach(r => {
const tr = body.insertRow();
columns.forEach(c => { tr.insertCell().textContent = r[c] ?? ''; });
});
return table;
}
document.getElementById('out').replaceChildren(renderTable([{ name: 'Ali', city: 'Lahore' }], ['name', 'city']));Create rows with textContent, so the data cannot inject HTML.
function formToJSON(form) {
const data = {};
for (const [key, value] of new FormData(form)) {
if (key in data) data[key] = [].concat(data[key], value);
else data[key] = value;
}
return data;
}Turn any form into a plain object. Repeated names (checkboxes) become arrays.
async function secureFetch(url, options) {
const res = await fetch(url, options);
if (res.status === 401) {
sessionStorage.setItem('after-login', location.pathname + location.search);
location.assign('/login');
throw new Error('Session expired');
}
return res;
}Send the visitor to the login page and bring them back afterwards.
async function request(url, options) {
const res = await fetch(url, options);
if (res.ok) return res.json();
let message = 'Something went wrong (' + res.status + ')';
try {
const body = await res.json();
if (body && body.error) message = body.error;
} catch (e) { /* body was not JSON */ }
throw new Error(message);
}Servers often explain the problem in the body. Show it.
async function toggleLike(btn) {
const wasLiked = btn.classList.contains('liked');
btn.classList.toggle('liked'); // instant feedback
try {
const res = await fetch('/api/like/' + btn.dataset.id, { method: wasLiked ? 'DELETE' : 'POST' });
if (!res.ok) throw new Error('failed');
} catch (e) {
btn.classList.toggle('liked', wasLiked); // rollback
}
}Update the screen first, send the request, and undo if it fails.
async function saveAll(rows) {
const saved = [];
for (const row of rows) {
const res = await fetch('/api/rows', { method: 'POST', body: JSON.stringify(row) });
if (!res.ok) break; // stop at the first failure
saved.push(row.id);
}
return saved;
}Use for...of with await when each request depends on the previous one.
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms));
return Promise.race([promise, timeout]);
}
withTimeout(fetch('/api/slow'), 3000).then(r => r.json()).catch(e => console.log(e.message));Whichever finishes first wins.
async function loadPanels() {
const urls = ['/api/users', '/api/orders', '/api/stats'];
const results = await Promise.allSettled(urls.map(u => fetch(u).then(r => { if (!r.ok) throw new Error(u); return r.json(); })));
results.forEach(function (r, i) {
const el = document.getElementById('panel' + i);
el.textContent = r.status === 'fulfilled' ? 'OK' : 'Failed to load';
});
}Promise.all stops at the first failure. allSettled gives you every result.
async function mapLimit(items, limit, worker) {
const results = [];
let next = 0;
async function run() {
while (next < items.length) {
const i = next++;
results[i] = await worker(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
return results;
}
mapLimit([1, 2, 3, 4, 5, 6], 2, id => fetch('/api/item/' + id).then(r => r.json()));Run many requests, but only a few at the same time.
function toCSV(rows) {
const esc = v => '"' + String(v).replace(/"/g, '""') + '"';
return rows.map(r => r.map(esc).join(',')).join('\r\n');
}
function saveCSV(rows, name) {
const blob = new Blob(['' + toCSV(rows)], { type: 'text/csv;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
}No server needed when the data is already on the page.
async function download(url, filename) {
const res = await fetch(url, { credentials: 'same-origin' });
if (!res.ok) throw new Error('Download failed');
const blob = await res.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
}Fetch the file as a blob, then click a temporary link.
function uploadWithProgress(file, onProgress) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
};
xhr.onload = function () { xhr.status < 300 ? resolve(xhr.responseText) : reject(new Error('HTTP ' + xhr.status)); };
xhr.onerror = function () { reject(new Error('Network error')); };
const fd = new FormData();
fd.append('file', file);
xhr.send(fd);
});
}fetch cannot report upload progress yet, XHR can.
const pick = document.getElementById('pick');
const img = document.getElementById('preview');
pick.addEventListener('change', function () {
const file = pick.files[0];
if (!file || !file.type.startsWith('image/')) return;
if (img.dataset.url) URL.revokeObjectURL(img.dataset.url);
const url = URL.createObjectURL(file);
img.dataset.url = url;
img.src = url;
});Show the chosen image immediately, then free the memory.
const input = document.getElementById('photo');
input.addEventListener('change', async function () {
const file = input.files[0];
if (!file) return;
if (!/^image\/(png|jpeg|webp)$/.test(file.type)) return alert('Please choose a PNG, JPG or WebP image.');
if (file.size > 2 * 1024 * 1024) return alert('Maximum size is 2 MB.');
const fd = new FormData();
fd.append('photo', file);
const res = await fetch('/api/upload', { method: 'POST', body: fd });
document.getElementById('msg').textContent = res.ok ? 'Uploaded' : 'Failed';
});Check the type and size in the browser, but always check again on the server.
let timer = null;
async function refresh() {
if (document.hidden) return;
try {
const data = await (await fetch('/api/notifications')).json();
document.getElementById('badge').textContent = data.items.length;
} catch (e) {}
}
document.addEventListener('visibilitychange', function () {
if (!document.hidden) refresh(); // catch up immediately
});
timer = setInterval(refresh, 10000);
refresh();Do not waste requests when nobody is looking.
function startPolling(url, onData, every = 5000) {
let stopped = false, timer;
async function tick() {
if (stopped) return;
try { onData(await (await fetch(url)).json()); } catch (e) {}
timer = setTimeout(tick, every);
}
tick();
return () => { stopped = true; clearTimeout(timer); };
}
const stop = startPolling('/api/status', d => console.log(d), 3000);
// stop();Use a recursive setTimeout, so a slow reply never overlaps the next one.
async function getCached(url, ttlMs = 5 * 60 * 1000) {
const key = 'c:' + url;
try {
const hit = JSON.parse(sessionStorage.getItem(key));
if (hit && Date.now() - hit.t < ttlMs) return hit.v;
} catch (e) {}
const value = await (await fetch(url)).json();
try { sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), v: value })); } catch (e) {}
return value;
}Keep the answer for a few minutes, then ask again.
const cache = new Map();
async function cachedJSON(url) {
if (cache.has(url)) return cache.get(url);
const promise = fetch(url).then(r => r.json()); // store the promise: even parallel calls share it
cache.set(url, promise);
try { return await promise; }
catch (e) { cache.delete(url); throw e; }
}Do not ask for the same data twice.
let page = 0, loading = false;
const observer = new IntersectionObserver(async function (entries) {
if (!entries[0].isIntersecting || loading) return;
loading = true;
const data = await (await fetch('/api/posts?page=' + (++page))).json();
data.items.forEach(i => document.getElementById('feed').insertAdjacentHTML('beforeend', '<p>Post ' + Number(i) + '</p>'));
loading = false;
if (!data.items.length) observer.disconnect();
}, { rootMargin: '300px' });
observer.observe(document.getElementById('sentinel'));Watch an empty element at the bottom. When it becomes visible, load more.
let page = 0;
const btn = document.getElementById('more');
async function more() {
btn.disabled = true;
const data = await (await fetch('/api/posts?page=' + (++page))).json();
data.items.forEach(i => {
const li = document.createElement('li');
li.textContent = 'Post ' + i;
document.getElementById('posts').append(li);
});
if (data.items.length < 10) btn.hidden = true;
btn.disabled = false;
}
btn.addEventListener('click', more);
more();Append the next page and hide the button when there is nothing left.
async function loadPage(page) {
const res = await fetch('/api/items?page=' + page + '&per_page=10');
const data = await res.json();
const list = document.getElementById('list');
list.replaceChildren(...data.items.map(i => Object.assign(document.createElement('li'), { textContent: 'Item ' + i })));
const pages = data.pages || 3;
document.getElementById('pager').replaceChildren(...Array.from({ length: pages }, (_, n) => {
const b = document.createElement('button');
b.textContent = n + 1;
b.disabled = n + 1 === page;
b.onclick = () => loadPage(n + 1);
return b;
}));
}
loadPage(1);Load a page, redraw the list and the page buttons.
const form = document.getElementById('order');
let busy = false;
form.addEventListener('submit', async function (e) {
e.preventDefault();
if (busy) return;
busy = true;
const btn = form.querySelector('button');
btn.disabled = true;
try {
await fetch('/api/order', { method: 'POST', body: new FormData(form) });
} finally {
busy = false;
btn.disabled = false;
}
});Block a second click while the first request is still running.
async function submitForm(form) {
form.querySelectorAll('.err').forEach(e => e.remove());
const res = await fetch(form.action || '/api/register', { method: 'POST', body: new FormData(form) });
if (res.status === 422) {
const { errors } = await res.json(); // { email: 'Invalid email', ... }
Object.entries(errors).forEach(([name, msg]) => {
const input = form.elements[name];
if (!input) return;
const span = document.createElement('span');
span.className = 'err';
span.textContent = msg;
input.after(span);
input.setAttribute('aria-invalid', 'true');
});
return false;
}
return res.ok;
}The server sends errors per field. Put each next to its input.
const csrf = document.querySelector('meta[name="csrf-token"]').content;
function post(url, data) {
return fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf },
body: JSON.stringify(data)
});
}
post('/api/delete', { id: 3 });Read the token from a meta tag and send it in a header.
async function api(path, { method = 'GET', body, headers = {} } = {}) {
const opts = { method, headers: { Accept: 'application/json', ...headers } };
if (body !== undefined) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(body);
}
const res = await fetch('/api' + path, opts);
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || 'HTTP ' + res.status);
err.status = res.status;
err.data = data;
throw err;
}
return data;
}
api('/users', { method: 'POST', body: { name: 'Ali' } }).then(console.log);One function for every call: JSON in, JSON out, one error format.
async function fetchRetry(url, options = {}, tries = 3) {
let lastError;
for (let i = 0; i < tries; i++) {
try {
const res = await fetch(url, options);
if (res.status < 500) return res; // success or a client error: do not retry
lastError = new Error('HTTP ' + res.status);
} catch (e) {
lastError = e;
}
await new Promise(r => setTimeout(r, 200 * (i + 1)));
}
throw lastError;
}Try again a few times for network errors and 5xx, but never for 4xx.
async function fetchWithTimeout(url, ms = 8000, options = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fetch(url, { ...options, signal: controller.signal });
} catch (err) {
if (err.name === 'AbortError') throw new Error('Request timed out after ' + ms + ' ms');
throw err;
} finally {
clearTimeout(timer);
}
}fetch waits forever by default. Add your own limit.
let controller = null;
async function search(term) {
if (controller) controller.abort();
controller = new AbortController();
try {
const res = await fetch('/api/search?q=' + encodeURIComponent(term), { signal: controller.signal });
return await res.json();
} catch (err) {
if (err.name === 'AbortError') return null; // expected
throw err;
}
}Cancel the old request when a new one starts, so a slow old reply never overwrites a new one.