views:

60

answers:

2

I have a form. I want to add an event handler using jquery.

$("form").submit(function blah() {
   $.post('ping-me-please.php', params, function (response) {
       // only submit the form once this goes through!
   });

}

How can I make this happen?

+5  A: 

Like this:

$("form").submit(function (e) {
    var form = $(this);

    if (!form.data('pinged')) {
        e.preventDefault(); // Cancel the submit
        $.post('ping-me-please.php', params, function (response) {
            // only submit the form once this goes through!

            // First we set the data, then we trigger the submit again.
            form.data('pinged', true).submit();
        });
    }
}
Doug Neiner
A: 
var postWasSent = false;
$("form").submit(function blah() {           
   if (!postWasSent)
   {
      $.post('ping-me-please.php', params, function (response) {
         postWasSent=True;
         $("form").submit();
      });
      return false;
   }

}
dmitko
This requires multiple presses of the submit button, or synchronous post.
sje397
thanks, edited.
dmitko