Search code examples
javascriptjqueryhtmlajaxloader

Delay jQuery Ajax loader for 3 seconds after submit button is pushed


I'm using a simple jQuery to show an animation DIV created with CSS after SUBMIT button is pushed. My issue is that when the server response is fast, the DIV is shown for justs some milliseconds. I'd like to display it for at least 3 seconds, regardless if the server response is fast or slow.

HTML:

<form class="search_cars" action="http://www.domain.com/searchresults" method="get">

    <label>
        <select name="model">
            <option value="" selected="selected">Select Make</option>
            <option value="Acura">Acura</option>
            <option value="...">...</option>
        </select>
    </label>

    <label>
        <select name="type">
            <option value="" selected="selected">All Models</option>
            <option value="...">..models script...</option>
        </select>
    </label>

    <label><input name="zip" type="tel" maxlength="5" id="zip" placeholder="zip code" /></label>

    <label><input name="submit" type="submit" value="search" class="search_button" /></label>

</form>

jQUERY:

$(".search_button").click(function(e) {
    $('#loadingProgressG').show();
    $.ajax({
        success: function(data) {
            $('#loadingProgressG').hide();
        },
        error: function() {
            $('#loadingProgressG').hide();
        }
    });
});

Looking at other threads at StackOverflow, I already tried this possible solution, changing:

$('#loadingProgressG').hide();

By

$('#loadingProgressG').delay(3000).hide(400);

But it didn't work. Also tried changing the same line by:

setTimeout(function() {
    $('#loadingProgressG').hide();
}, 3000);

And nothing. The most probably is that I'm doing something wrong, I'm not a jQuery guru. Any help or advice is appreciated.

** I just noticed that using setTimeout works for the time set, only if some form validation stop the process.


Solution

  • Your example should work. My only guess is that since you have the submit button tied to a form, it's processing the form as opposed to successfully running the function after the AJAX is completed.

    In order to prevent the form from processing, you want to preventDefault() then run what you want to run.

    EDIT: Assuming that you need the form to actually process, you would submit the form after the 3000 setTimeout. Like such:

    JSFiddle: DEMO

    For the submit button, use a <button> instead:

    <label><button class="search_button">search</button></label>
    

    Then do the following for the JavaScript:

    $(".search_cars").submit(function (e) {
        e.preventDefault();
    
        var form = this;
        $("#loadingProgressG").show();
        setTimeout(function () {
            $("#loadingProgressG").hide();
            form.submit();
        }, 3000); // in milliseconds
    });