Cancel AJAX Requests with AbortController
AbortController lets code cancel a Fetch request. This is useful when a user changes a search query, navigates away from a component, or starts a newer request that replaces older work.
Abort a request
const controller = new AbortController();
const response = await fetch('/api/report.php', {
signal: controller.signal
});
// Later, when the result is no longer needed:
controller.abort();
A cancelled Fetch promise rejects, commonly with an AbortError. Handle that separately from genuine network failures so the interface does not show a misleading error.
Avoid stale results
Keep the active controller for a component or request sequence. Abort the previous request before starting a replacement. Also consider a request identifier when multiple independent operations can complete out of order.
Cancellation is a client-side control; the server may already have received and started processing the request. Do not use it as a substitute for server-side transaction or job management.