$ .post () does not have time to start?

I am trying to send data from a form to an external script before submitting the form, but I cannot get the data to receive an external script, unless I am return false;in 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. */
  });
});
+3
source share
2 answers

Today I faced the same problem. As Mark says, this is because the ajax call is asynchronous. The simplest solution is to make it synchronous.

Use .ajaxSetup () before any ajax calls like:

$.ajaxSetup({async: false});
+8
source

Sending to two endpoints

I would try something like this instead of using async: true. Although this is noticeably more complex, it does 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

, , $.post, JavaScript , JavaScript.

, JavaScript , , submit.

return false;

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

  e.preventDefault();
}

, ​​ $.post, JavaScript . , .

preventDefault return false, , , . return false e.preventDefault(); e.stopPropagation();

+2
source

Source: https://habr.com/ru/post/1702858/


All Articles