Urbley
Urbley

Reputation: 716

Having a show and hide in the same function doesn't seem to work

I searched around but couldn't find a solution for this. I'm sure it's simple but the solution is eluding me :/

I have a function assigned to .click() on an Html button input. Everything in the function is working fine except the show and hide aren't triggering in the correct order. My little spinner image is only appearing at the end of the function run it seems and it doesn't hide again.

In case it isn't obvious, what I'm trying to achieve is having the spinner image showing until the php output is returned.

<div id="results" style="padding: 20px;"></div>

header date <input type="text" id="headerDate" name="headerDate" size="15" value="20130101" />
#rows <input type="text" id="numRows" name="numRows" size="15" value="10000" />
<input type="button" value="GO" id="goButton" />
<img id="spinner" style="display: none;" src="images/spinner.gif" border="0" width="30" height="30" alt="loading..." />

<script>
    $('#goButton').click( function() {
        $('#spinner').show();

        $.ajax({
            url: 'do_something.php',
            type: 'POST',
            data: { 'headerDate': $('#headerDate').val(), 'numRows': $('#numRows').val() },
            dataType: 'html',
            success: function(data) {
                $('#results').html(data);
            },
            error: function() {
                $('#results').html("Something went wrong!");
            }
        });

        $('#spinner').hide();
    });
</script>

I'm a bit of a jQuery noob so please forgive me if this is obvious.

Upvotes: 0

Views: 65

Answers (1)

Adween
Adween

Reputation: 2820

You need to put it in the success or fail

$.ajax({
        url: 'do_something.php',
        type: 'POST',
        data: { 'headerDate': $('#headerDate').val(), 'numRows': $('#numRows').val() },
        dataType: 'html',
        success: function(data) {
            $('#results').html(data);

            $('#spinner').hide();
        },
        error: function() {
            $('#results').html("Something went wrong!");

            $('#spinner').hide();
        }
    });

Upvotes: 3

Related Questions