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 React pattern optimizes performance in functional components by preventing unnecessary re-renders using the useMemo and useCallback hooks. It is ...

React Performance Optimization Using useMemo And useCallback Hooks

JavaScript
This React code snippet utilizes the Context API along with the useMemo hook to optimize performance by sharing data between components efficiently. I...

Optimizing React Performance With Context API And useMemo

JavaScript
This code snippet demonstrates how to optimize React hooks using useCallback and useMemo to prevent unnecessary re-renders and improve performance. It...

React Performance Optimization Using UseCallback And UseMemo Hooks