How to show loading-div after submitting a form with jQuery?

user3745073 picture user3745073 · Jun 16, 2014 · Viewed 33.3k times · Source

I am new at Javascript and jQuery. I want to show a "loading-gif" after the user submitted a form but can't figure out why my code is not working. That's the situation:

  • the form has the id="form"
  • the loading-div has the id="loading" and the style="display:none" (and some others of course)
  • the submit-button has the class="formtrigger" (and no type="submit")

That's my javascript (initialized after jquery at the bottom of the html-page):

    $('.formtrigger').click(function() {
      $('#loading').show();
      $('#form').submit();
    });

When I click the button, the form is submitted, but the loading-div doesn't appear. I tried the line "$('#loading').show();" without binding it on the click-event and it worked. I also tried this code:

$('.formtrigger').click(function() {
    alert('blablabla');
    $('#form').submit();
});

and both statements worked! First the alert is shown and then the form is submitted. Why does the other code not work?

Thanks in advance.

EDIT: I've also tried the following variations without success

$('.formtrigger').click(function() {
    $('#form').submit();
});
$('#form').submit(function() {
    $('#loading').show();
});

and

$('.formtrigger').click(function() {
    $('#loading').show();
    window.setTimeout($('#form').submit(), 5000);
});

and

 //HTML
 <button type="submit">...</button>
 //JS
 $('#form').submit(function() {
     $('#loading').show();
 });

Answer

urbz picture urbz · Jun 16, 2014

In your .submit(), show your loading spinner:

$("#loading").show();

And after your .submit() is done, hide it:

$("#loading").hide();

And make your spinner display: none; by default since the jQuery above simply changes the css properties for your specified element.


I provided you with a simple demo where I have an AJAX function echoing your message from the text input. It will show a loading spinner until it reaches success.

Fiddle Demo