Back to Snippets

Debounced AJAX Search with jQuery

JavaScript JavaScript / jQuery April 6, 2026

Debounced AJAX search input using jQuery — 300ms delay, minimum 2 characters, loading state, localized strings via wp_localize_script.

Snippet Stats

Lines 40
Characters 1,153
Read 2 mins
javascript • 40 lines
(function($) {
    'use strict';

    var timer = null;
    var $input   = $('#search-input');
    var $results = $('#search-results');

    $input.on('input', function() {
        var query = $.trim($(this).val());

        clearTimeout(timer);

        if (query.length < 2) {
            $results.empty();
            return;
        }

        timer = setTimeout(function() {
            $.ajax({
                url:  mySearchData.ajaxUrl,
                type: 'POST',
                data: {
                    action:   'site_search',
                    security: mySearchData.nonce,
                    query:    query
                },
                beforeSend: function() {
                    $results.html('' + mySearchData.i18n.searching + '');
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        $results.html(response.data.html);
                    } else {
                        $results.html('' + mySearchData.i18n.noResults + '');
                    }
                }
            });
        }, 300);
    });
})(jQuery);

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This code snippet demonstrates how to use the React use Memo hook to optimize component performance by memoizing expensive function calls and preventi...

Optimizing React Component Performance with the Use Memo Hook

JavaScript
This React hook handles asynchronous data fetching from APIs, managing loading, error, and success states. It utilizes the useEffect and useCallback h...

React Hook For Asynchronous Data Fetching With Error Handling

JavaScript
This React code snippet demonstrates an optimization technique using memoization and callbacks to prevent unnecessary re-renders. It is particularly u...

React Optimization Technique Using Memoization And Callbacks