How to add a ” waiting” icon for an ajax in WP frontend?

You can use the inbuilt spinner class :

Add the class to the HTML where you want the spinner to appear, for example after your search button :

<button type="button" id="searchsubmit">Search Button</button>
<span class="spinner"></span> <!-- Add this spinner class where you want it to appear--> 

In jQuery you should add the is-active class to the spinner immediately after the click event; then in your ajax post response you remove the is-active class :

jQuery(document).ready(function($) {

    $('#searchsubmit').click(function(e){ 

        e.preventDefault();

         $(".spinner").addClass("is-active"); // add the spinner is-active class before the Ajax posting 

        $.post(
            WPaAjax.ajaxurl,
            {
                action : 'your_action',
                data : data
            },
            function( response ) {

                 $(".spinner").removeClass("is-active"); // remove the class after the data has been posted 

            }
        );
    });

});

Hope that helps. See more from WordPress core docs

Leave a Comment