0

I have a loading message and a success message that I want to fade in and fade out before the form gets submitted. I can't really get the code right to show these messages for a couple of seconds then submit the form as usual with Ajax. I have tried to connect the submit button like this.

jQuery(document).ready(function (e) {
    jQuery( "#submitbutton" ).click(function() {
           e.preventDefault();
           jQuery('#loadingMessage').fadeIn(1000);
           jQuery('#loadingMessage').hide().delay(1000);
           jQuery('#saveMessage').show().delay(2000).fadeOut(1000);
       setTimeout( function () { 
            jQuery("form[id=postorder]").submit();
        }, 4000);
    });
});

Or this, this just an example, I have tried a few.

jQuery(document).ready(function (e) {
    jQuery("form[id=postorder]").submit({
           e.preventDefault();
           jQuery('#loadingMessage').fadeIn(1000);
           jQuery('#loadingMessage').hide().delay(1000);
           jQuery('#saveMessage').show().delay(2000).fadeOut(1000);
       setTimeout( function () { 
            [Submit form here]
        }, 4000);
    });
});

The messages works fine. Grateful for any help!

sorak
  • 2,587
  • 2
  • 14
  • 24
Fredrik
  • 343
  • 2
  • 11

1 Answers1

1

You can do something like this

jQuery(document).ready(function (e) {
    jQuery( "#submitbutton" ).click(function() {
           jQuery('#loadingMessage').fadeIn(2000, function(){
            jQuery('#loadingMessage').hide(2000, function(){
              jQuery('#saveMessage').show(2000).fadeOut(2000, function(){
                jQuery("form[id=postorder]").submit();
              });
            });
           });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="loadingMessage" style="display:none;">Loading Message</p>
<p id="saveMessage"  style="display:none;">Save Message</p>

<form id="postorder" action="" method="post">
  <input type="button" id="submitbutton" value="submit">
</form>

jQuery is non blocking as it is a Javascript library.

Non blocking means it will not wait for the previous line to complete it's work. It will move to the next line while the previous line code is stilling working.

So you need to use callback functions to do something sequentially in a situation like this.

Hope this helps :)

Mahbubul Islam
  • 972
  • 1
  • 8
  • 21
  • 1
    Works prefect! Smart to attach the Ajax to a button instead of a Type=Submit and then run the submit in a function after the last message. Thank you! – Fredrik Mar 15 '18 at 15:43