Elliot
Elliot

Reputation: 13845

Submitting two forms through 1 action in javascript using JQuery

So this is kind of complicated. I have a form that I need to submit the results to two different places.

The first place is an ajax call, where I send the results to a PHP page. The second is just submitting the form, business as usual.

Here is my javascript:

<script type="text/javascript">

  $(function() {
    $("#requestaction").click(function() {
      var fname = $("input#first_name").val();
      var lname = $("input#last_name").val();
      var email = $("input#email").val();
      var phone = $("input#phone").val();
      var oid = $("input#oid").val();
      var retURL = $("input#retURL").val();

      var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid + '&retURL=' + retURL;
      //alert (dataString);return false;
      $.ajax({
          type: "POST",
          url: "http://www.myurl.com/custom/callgateway.php?first_name=" + fname + "&last_name=" + lname,
          data: dataString
      });

      $("#requestaction").click(function() {
          $("#oid").delay(1000);
          $("#nashform").submit();
      });

    return false;
    });

  });
    </script>

So what I want to have happen is for the ajax call to send the results to that page. And then I want a few second delay, or however long it takes until thats complete, and I want the form with #nashform ID to submit. It seems that I can make both happen separately, but when I try this code at the same time - only the #nashform code fully goes through, the ajax never gets a chance.

Any suggestions?

Upvotes: 0

Views: 390

Answers (4)

Tahir Akhtar
Tahir Akhtar

Reputation: 11645

$.ajax({
type: "POST",
url: "http://www.myurl.com/custom/callgateway.php?first_name=" + fname + "&last_name=" + lname,
data: dataString,
success: thesubmitfunction
});

Make the form submission in the thesubmitfunction while will be called when ajax call finishes successfully.

Upvotes: 1

Rudu
Rudu

Reputation: 15892

Rather than a delay, why don't you add the submitting of nashform to the callback that's made once the AJAX post is complete? That way you won't potentially cut the AJAX transfer mid or pre-post.

You could also consider making both posts using AJAX... both posting at the same time, once both are complete the page could update (or even redirect) giving the illusion to the user that the data was submitted as normal.

Upvotes: 0

AJ.
AJ.

Reputation: 28204

You need a callback function to submit your form after ajax() returns.

Upvotes: 0

Fosco
Fosco

Reputation: 38526

Put the form submit in the success callback of the ajax call:

$.ajax({
    type: "POST",
    url: "http://www.myurl.com/custom/callgateway.php?first_name=" + fname + "&last_name=" + lname,
    data: dataString,
    success: function(response) { $("#nashform").submit(); }
    });

Upvotes: 6

Related Questions