Replace jQuery AJAX with fetch() and AbortController in WordPress themes
WordPress AJAX handlers still run through admin-ajax.php on the server, but the client code can drop $.ajax() for the native fetch() with async/await. Two details are specific to WordPress. The wp_send_json_*() functions report success or failure in the success field of the JSON, so checking the HTTP status is not enough. And for live search there is AbortController, which cancels a request that is still running when the user types the next character, so a slow old response cannot overwrite a newer one.
Problem: Live search built with $.ajax() has nested callbacks, does not cancel outdated requests, and keeps jQuery only for HTTP calls.
Solution: Use fetch() with a debounce of the input, check both response.ok and success, cancel the previous request with AbortController, and build the results with DOM methods.
The script
The handler on the server (wp_ajax_my_live_search with the nonce check) is described in verifying nonces in AJAX handlers; it answers with wp_send_json_success() and a list of title and url.
// js/live-search.js
( function () {
const input = document.getElementById( 'live-search' );
const results = document.getElementById( 'search-results' );
if ( ! input || ! results ) {
return;
}
let timer = null;
let controller = null;
input.addEventListener( 'input', () => {
clearTimeout( timer );
timer = setTimeout( doSearch, 350 );
} );
function showMessage( text ) {
results.textContent = '';
const p = document.createElement( 'p' );
p.textContent = text;
results.appendChild( p );
}
async function doSearch() {
const query = input.value.trim();
if ( controller ) {
controller.abort(); // cancel the previous request
}
if ( query.length < 2 ) {
results.textContent = '';
return;
}
controller = new AbortController();
showMessage( 'Searching…' );
try {
const body = new FormData();
body.append( 'action', 'my_live_search' );
body.append( 'nonce', myAjax.nonce );
body.append( 'search', query );
const response = await fetch( myAjax.ajaxurl, { method: 'POST', body, signal: controller.signal } );
if ( ! response.ok ) {
throw new Error( 'HTTP ' + response.status );
}
const json = await response.json();
if ( ! json.success ) {
throw new Error( 'Server error' );
}
if ( ! json.data.length ) {
showMessage( 'No results found.' );
return;
}
results.textContent = '';
json.data.forEach( ( item ) => {
const a = document.createElement( 'a' );
a.href = item.url;
a.textContent = item.title;
results.appendChild( a );
} );
} catch ( error ) {
if ( error.name !== 'AbortError' ) {
showMessage( 'Search failed. Please try again.' );
}
}
}
}() );
An aborted request rejects with an AbortError, which is expected and is ignored. The results are built with textContent, not with innerHTML from server strings, so a post title with HTML in it cannot inject markup.
The PHP side of the script
<?php
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script( 'live-search', get_stylesheet_directory_uri() . '/js/live-search.js', array(), '1.0', true );
wp_localize_script( 'live-search', 'myAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my_ajax_nonce' ),
) );
} );
Do not hardcode /wp-admin/admin-ajax.php: in a subfolder install or with a moved admin the path is different, admin_url() always gives the right one.
NOTE: For the results, mark the container as a live region (aria-live="polite") so screen readers announce the new results and the messages. And if the script no longer uses jQuery at all, remove 'jquery' from its dependencies: then the page may not need jQuery at all.