Two forms one submit - Submit, delay, submit

2019-08-17 13:19发布

问题:

I am trying to submit two forms at once (one goes to db and the other goes to fpdf to make labels). I use jquery to copy the variables from the first form to hidden inputs on the second form. I have seen this question asked a couple times on here but none of the answers have helped. I use the 'fake' ajax method - ie: I set the form target to a hidden iframe on the same page. So I want to submit one form, then use a delay then submit the second form (because it's not working without the delay!)

So how do I add a delay to this code:

    $('#insert').submit(function() {
    //Delay here please, or is it timeout I need?
    $('#print').submit();
    });

<form id="insert" action="insert.php" target="hiddeniframe">
// a bunch of inputs
<input type="submit" value="submit">
</form>

<form id="print" action="pdf.php" target="hiddeniframe">
// a bunch of inputs
</form>

回答1:

It's not clear on what your scripts are doing / returning, but you can always use ajax for the first request, then use the iframe for the second request. Eg:

$('#insert').on('submit', function(e) {
  e.preventDefault();

  $.ajax({
    url: $(this).attr('action'),
    type: 'POST',
    data: $(this).serialize(),
    success: function() {
      // duplicate fields from first form into second form
      // as per whatever code you've already written

      // submit second form
      $('#print').submit();
    })
  });
});

This way the second form is submitted after the successful response of the first form.