Javascript – Form submit and Ajax at the same time using onsubmit

ajaxformsjavascriptjqueryPHP

i am sorry if this have been asked before, but i need to send my form data with both the form submit and a ajax call that fires off when clicking submit. The reason why is because the user get's redirected and i want to store det formdata to my database beforehand.

So i try to use the form onsubmit and fire of a javascript function that submits the formdata.
This does not work, the form is sent and no ajax call is made. So i try to take the ajax call out of the function and see if it works then and it does, on page refresh the ajax call is made and my database updated.

Here are som code:

HTML

<form id="danlevi" onsubmit="return senddata()" action='<?php echo esc_url( get_option( 'shopping_cart_url' ) ); ?>' method='post' enctype="multipart/form-data">
  <input type="text" name="first" />
  <input type="text" name="last" />
  <input type="text" name="e-mail" />
  <input type="text" name="phone" />
  <input type="text" name="street" />
  <input type="text" name="zip" />
  <input type="submit" value="send" />
</form>

javaScript

jQuery(document).ready(function() {
  function senddata() {
    var formdata = jQuery("#danlevi").serialize();
    var decoded = decodeURIComponent(formdata);
    strip = decoded.replace(/[\[\]]/g, "_");
    alert(strip);
    jQuery.ajax({
      type: "POST",
      url: 'dev/wp-content/themes/twentythirteen/custom/process_address.php',
      data: strip,
    });
  }
});

I have no idea why this is not working, what i want is for the page to wait until the ajax call is made, when done, send the form as usual.

If i use return false, it works. I hope that someone can explain what i obviously do wrong, and show me the way of doing this. The alert you see in this code is just for debugging.

Best Answer

Wait until the ajax completes then submit the form.

   jQuery(document).ready(function() {
      function senddata() {
        var formdata = jQuery("#danlevi").serialize();
        var decoded = decodeURIComponent(formdata);
        strip = decoded.replace(/[\[\]]/g, "_");
        alert(strip);
        jQuery.ajax({
          type: "GET",
          url: 'dev/wp-content/themes/twentythirteen/custom/process_address.php',
          data: strip,
          complete: function(){
              jQuery("#danlevi").submit(); //submit the form after ajax completes
          }
        });
        return false; //stop the form from initially submitting
      }
    });