Javascript – Show loading gif after submit button is clicked?

htmljavascriptjquery

I'm trying to show a loading gif after a user clicks submit on a form.

I have search endlessly for a good tutorial showing how it done.

I get half way there but the gif doesn't hold for long enough, do any one know of a good tutorial or the scripts need to complete this.

Best Answer

It's really simple. You have an image, initially hidden:

<img src="myloadingimage.gif" style="display: none;" id="loading_image">

You make an AJAX request:

$('#loading_image').show(); // show loading image, as request is about to start
$.ajax({
    url: '..',
    type: '..',
    complete: function() {
        // request is complete, regardless of error or success, so hide image
        $('#loading_image').hide();
    }
});

It's not rocket science, I promise. :)

EDIT: In response to your comment, this uses jQuery. You put the jQuery tag so I assume that is fine.

I also noticed I didn't fully address your original question, which is that you want to show the loading bar for what is presumably a regular form. If your form tag has an id of "myform", this should do it:

$('#myform').submit(function() {
    $('#loading_image').show(); // show animation
    return true; // allow regular form submission
});

You could also throw a line like this in:

$(':submit',this).attr('disabled','disabled');

If you want to stop users from clicking submit more than once. This should still be verified server-side but it is a nice superficial barrier of defense.