LOGBOOK

HELP

Quiz Entry - updated: 2026.07.05

How do you implement a type-ahead (autocomplete) station search with AJAX?

On each keystroke, JavaScript fires an AJAX call to /locations with the text typed so far, then shows the returned matches in a dropdown for the user to pick from.

AJAX just means making an HTTP request from JavaScript in the background and updating the page with the result — no full reload. Here, the handler reads the input's current value, builds the search URL (restricting to type=station), fetches, and hands the stations array to a function that renders the popup:

async function loadStationsBy() {
  const station = document.getElementById('station');
  const url = 'https://transport.opendata.ch/v1/locations?query='
    + station.value + '&type=station';

  const response = await fetch(url, {
    method: 'GET',
    signal: AbortSignal.timeout(5000)
  });

  if (response.ok) {
    const res = JSON.parse(await response.text());
    autocomplete(station, res.stations); // populate the dropdown
  }
}

The AbortSignal.timeout(5000) cancels the request if the API hasn't answered in 5 seconds, so a slow network can't freeze the search box.

Tip: Firing a request on every keystroke can flood the API. Production code usually debounces — waits until the user pauses typing — to send far fewer requests.

Go deeper:

From Quiz: WEBT / External Webservices | Updated: Jul 05, 2026