Loading GIF stops animation when submitting a form

2019-05-20 03:56发布

问题:

Check out this simple JSFiddle (ignore all the javascript code, this question here is only about the animated loading GIF).

I want to show the animated loading GIF before a form gets submitted.

I tried this:

setTimeout(function(){
 $('form[name="checkout-form"]').submit();
},1000);

And this works fine, the animated loading GIF appears for 1 second, however, it stops the animation as soon as the submit request has been sent.

What do I have to do in order to let the GIF animated until the page loads again (or until the response comes back from the page?)

回答1:

You need to AJAX the form. When you submit the form, the page and animations are unloaded.

So try

$(function() {
  $('form[name="checkout-form"]').on("submit",function(e) {
    e.preventDefault(); // stop the actual submission
    $("#animationgif").attr("src","submitting.gif?rnd="+new Date().getTime()).show();    
    $.post(this.action,$(this).serialize(),function() {
      $("#animationgif").attr("src","blank.gif").hide();    
    });
  });
});

The ?rnd="+new Date().getTime() is to make sure it starts from the beginning and can be removed if it is a looping ajax throbber