views:

110

answers:

2

I'm trying to send data from a form to an external script prior to submitting the form, yet I cannot seem to get the data to reach the external script unless I return false; on the form itself.

$(document).ready(function(){    

  // Handle Form-Submission
  $("#mainForm").submit(function(){  

    // Reset Error Array
    errors = new Array();

    /* Validation Code Removed - Not Relevant */     

    // Check if errors exist
    if (errors.length > 0) {
      return false;
    } else {
      $("div.errors").html("");
      $.post("post.php",{
        "First Name":name_first.val(),
        "Last Name":name_last.val(),
        "Home State":home_state.val(),
        "Primary Email":email_primary.val()}
      );
    }
    return false; /* Remove this line, and the $.post won't work. */
  });
});
+8  A: 

I ran into the exact same problem today. Like Marc says, it's because the ajax call is asynchronous. The simplest fix is to make it synchronous.

Use .ajaxSetup() before any ajax calls like such:

$.ajaxSetup({async: false});
Peter J
That works! Wow. I love StackOverflow. Spend 2 hours working on a problem, and get the answer within 10 minutes of posting it here.
Jonathan Sampson
Just be careful of synchronous - it will block the UI until the POST returns!
Jarrod Dixon
Definitely, it's only to be used in a scenario where you want to block the UI. Safe way is for your click/submit event to return true by default so non-Javascript browsers will still function properly.
Peter J
+2  A: 

Sending to two end points

I would try something like this instead of using async: true. Though it is notably more complicated, it would not freeze the interface.:

 $(document).ready(function(){           
  // Handle Form-Submission
 $("#mainForm").submit(function(e){  
    e.preventDefault();
    var $form = $(this);

    if($form.data('submitting')) return; // Avoid double submissions
    $(':submit').attr('disabled','disabled'); // Disable the submit button

    // Reset Error Array
    errors = new Array();

    /* Validation Code Removed - Not Relevant */        

    // Check if errors exist
    if (errors.length > 0) {;
      $(':submit').removeAttr('disabled'); // Enable the submit button
      return false;
    } else {
      $("div.errors").html("");
      $form.data('submitting',true); // Flag that a submission has started
      $.post("post.php",{
        "First Name":name_first.val(),
        "Last Name":name_last.val(),
        "Home State":home_state.val(),
        "Primary Email":email_primary.val()},
        function(){
          // remove our special handler and submit normally
          $form.unbind('submit').submit();
        }
      );
    }
  });
});

Original Answer

It seems your hangup is that you want to use $.post if JavaScript is enabled, but let the form function normally with JavaScript disabled.

However, since none of your JavaScript will run if it is disabled you don't have to worry about altering behavior in the submit function.

You can just leave your return false; statement, or use

$("#mainForm").submit(function(e){  
  // all your existing code

  e.preventDefault();
}

That will keep the form from submitting normally and will instead using your $.post method when JavaScript is enabled. If it is disabled it will submit normally.

preventDefault is preferred to return false if you want event bubbling to continue as normal, but keep the default browser action from continuing. return false is the equivalent of calling e.preventDefault(); e.stopPropagation();

Doug Neiner