Build Live Search with AJAX and Fetch
Live search requests matching results as a user types. Debouncing reduces unnecessary requests by waiting briefly after the last keystroke.
Debounced search
let timer;
const input = document.querySelector('#search');
input.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(runSearch, 250);
});
async function runSearch() {
const q = input.value.trim();
if (q.length < 2) return renderResults([]);
const params = new URLSearchParams({ q });
const response = await fetch(`/api/search.php?${params}`);
if (!response.ok) throw new Error('Search failed');
renderResults(await response.json());
}
Server-side search
Set a minimum and maximum query length, cap the result count, and use prepared statements. Escape wildcard characters if literal matching is required. Do not expose private records through a public search endpoint.
User experience
Show a loading state, an empty state, and a recoverable error. Use an accessible live region for result updates and avoid announcing every intermediate keystroke.