4

I want to have a timeout function so when a form is submitted the alert is displayed two seconds after the submit. The code I am using doesn't work:

$(document).ready(function() {
  $("#newsletter").submit(function() {
     setTimeout(function() {
      alert("submitted");             
    }, 2000);
   });
});

But when I change the 2000ms to 900 is seems to work fine:

$(document).ready(function() {
  $("#newsletter").submit(function() {
    setTimeout(function() {
     alert("submitted");              
   }, 900);
  });
});

How can I get the 2000ms to work?

Wouter J
  • 41,455
  • 15
  • 107
  • 112
DLO
  • 309
  • 2
  • 7
  • 17

3 Answers3

5

The only possible reason for this is that your form is getting submitted and the user is taken to the new page (the form's action) before the 2 seconds elapse.

As suggested in Thilo's comment, if showing the alert is unavoidable, submit it via AJAX so that the current page (containing the code to alert) remains intact and therefore executes.

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • And this breaks your code because after the page is destroyed (to go to the new page), it cannot run any Javascript anymore. – Thilo Mar 29 '13 at 09:42
  • 2
    A solution would be to not load an entirely new page, but submit the data via Ajax. – Thilo Mar 29 '13 at 09:44
  • It doesn't re-direct?
    – DLO Mar 29 '13 at 09:46
  • 1
    @DLO - Even though its the same page that is getting loaded, the fact is that it **is** getting reloaded - any JS code that was running before the reload will not continue automatically after reload. – techfoobar Mar 29 '13 at 09:47
  • @DLO Check here for an ajax solution [http://stackoverflow.com/a/2866127/474535](http://stackoverflow.com/a/2866127/474535) – bart s Mar 29 '13 at 09:48
0

You could change your code to this:

$(document).ready(function() {
  $("#newsletter").submit(function(event) {
     var element = this;
     event.preventDefault();
     setTimeout(function() {
      alert("submitted");

      //rest of the code

      element.submit();
    }, 2000);
   });
});

Snippet:

    $(document).ready(function() {
      $("#newsletter").submit(function(event) {
         event.preventDefault();
         var element = this;
         setTimeout(function() {
          alert("submitted");
           element.submit();
        }, 2000);
       });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form style="width:440px;" action="./" method="post" id="newsletter">
    <input type="text"/>
    <input type="submit" value="Submit"/>
</form>
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
0

You can use like this. The problem with your original code was that, it got submitted before the alloted time.

$(document).ready(function() {
    $("#newsletter").submit(function(e) {
        e.preventDefault();
        setTimeout(function() {
            alert("submitted");
        }, 2000);
    });
});
Sanjay
  • 1,595
  • 1
  • 17
  • 29