Atomiklan
Atomiklan

Reputation: 5434

Ajax busy indicator

How can I add a busy indicator before the Ajax popup appears on screen? I have been trying to follow several examples, but they are overly complex and very confusing for what seems should be an easy fix. Can anyone please help? Very new to Ajax. Thank you!

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('.button').click(function(){
            var clickBtnValue = $(this).val();
            var ajaxurl = 'auto.php',
            data =  {'action': clickBtnValue};
            $.post(ajaxurl, data, function (response) {
                alert(response);
            });
        });

    });
    </script>
</head>
<body>
    <input type="submit" class="button" name="Start" value="Start" />
</body>
</html>

Upvotes: 0

Views: 281

Answers (1)

Joshua K
Joshua K

Reputation: 2537

You have to add the indicator when starting the ajax call and remove it when the call returns.

But you should fix your html (input element is only valid inside a form tag) and then you have to prevent the form submission. If you follow this rules your code looks like this:

$(document).ready(function(){
    $('.button').click(function(evt){
       // preventing the form submission
        evt.preventDefault();
        var clickBtnValue = $(this).val();
        var ajaxurl = 'auto.php',
        data =  {'action': clickBtnValue};
        // add indicator here (before the ajax request starts)
        var $indicator = $('<div>Ajax in progress...</div>').appendTo('body');
        $.post(ajaxurl, data, function (response) {
            // removing the indicator inside the success handler of the ajax call.
            $indicator.remove();
            alert(response);
        });
    });
});

Upvotes: 1

Related Questions