LatentDenis
LatentDenis

Reputation: 2991

jQuery loading animation hide(), show() error

my html code:

<div id="success_message" style="display:none">
    <p>Good job!</p>
</div>
<div id="my-form">
    <form>
        <input>....... (there's lots of inputs)
            <input id="my-btn" type="submit" name="" value="Send" />
            <img id="loading-img" src="images/loading.gif" style="display:none"/>
    </form>
</div>

Then I have my javascript at the end:

<script>

    jQuery('#my-btn').click(function () {
        jQuery('#my-btn').hide();
        jQuery('#loading-img').show();
    });


    jQuery("#my-btn").click(function (e) {

        var str = ......... (there's a string)
        jQuery.ajax({
            type: "post",
            url: "/insert.php",
            data: str,
            dataType: "json",
            success: function (result) {
                if (result.success == 1) {
                    jQuery('#loading-img').hide();
                    jQuery('#my-form').hide();
                    jQuery('#success-message').show();
                } else {
                    jQuery('#my-btn').show();
                }
            }
        });
    });
</script>

The problem isn't in the str being passed in or the ajax call, because I've tested with my code and data, and everything gets executed, and goes to to "if(result.success == 1)" part of the code..

The problem is that when I lick the "my-btn", it makes the "my-btn" hide, but the loading image doesn't appear and the form that the div is in doesn't hide, and then the success message doesn't show as well...

What am I doing wrong and how can I make my code better?

Upvotes: 0

Views: 681

Answers (2)

mr_sudaca
mr_sudaca

Reputation: 1176

As Roman said, you can add a "remove" submit button default behaviour, or, just turn it into a button. Also you can hide the button and display the loading message in the same click event:

    jQuery("#my-btn").click(function (e) {
      jQuery('#loading-img').show();
      jQuery('#my-btn').hide();
    .
    .
    .

something like this

Upvotes: 1

Roman Hutnyk
Roman Hutnyk

Reputation: 1549

You're using button (submit), which reloads your page. You might use either e.preventDefault(); or return false; in order to avoid reload. See the sample here :

jQuery('#my-btn').click(function () {
        jQuery('#my-btn').hide();
        jQuery('#loading-img').show();

        // put ajax call here....

        return false;
    });

Also I'd place all the code into one method. There is no reason to have two click handlers.

Upvotes: 2

Related Questions