AJAX Autocomplete and Search Suggestions
Autocomplete offers suggestions while a user enters a query. A robust implementation supports keyboard navigation, cancellation of stale requests, and safe text rendering.
Cancel outdated requests
let controller;
async function suggest(q) {
controller?.abort();
controller = new AbortController();
const params = new URLSearchParams({ q });
const response = await fetch(`/api/suggest.php?${params}`, {
signal: controller.signal
});
if (!response.ok) throw new Error('Suggestions unavailable');
return response.json();
}
Keyboard and accessibility
Use a combobox pattern with clear labels, aria-expanded, and an active descendant. Support Arrow Up, Arrow Down, Enter, and Escape. Keep focus in the input while moving through suggestions.
Security and performance
Render suggestion labels with textContent, not unsanitized HTML. Limit query length and result count, debounce requests, and ensure the endpoint returns only data the current user may access.