AJAX Search

AJAX Autocomplete and Search Suggestions

Implement autocomplete suggestions with keyboard support, request cancellation, and safe rendering.

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.

Share this page Help other developers discover this resource.