简体   繁体   中英

Submit two forms with single submit button (JSON)

I have two forms, one on the main page, and another one in iframe. I would like to submit both at the same time with the single submit button.

Here is the one which is on the main page:

<form id="loginForm" method="post" action="http://www.example.com/"  >
<div class='hiddenFields'>
<input type="hidden" name="visitor_action" value="login" />
<input type="hidden" name="RET" value="http://www.example.com" />
<input type="hidden" name="site_id" value="1" />
<input type="hidden" name="csrf_token" value="2129d6db6941fc2f95b854720f77134f7753d1d7" />
</div>

<div id="sign_up_form">
<label>E-mail: <input type="text" name="username" id="username"/></label>
<div id="actions">
<input name="submit" type="submit" value="Sign In" />
</div>
<div id="login-error"></div>
</div>
</form>

Ajax/Json part:

$(document).ready(function(){
$('#loginForm').ajaxForm({
dataType: 'json',
success: function(data) {
if (data.success) {
window.location.replace("/cabinet/");
} else {
                    $('#login-error').delay(500).fadeIn('slow').html(data.errors.login);
                    $('#login-error').delay(2500).fadeOut('slow');
         }
      }
   });
});

And IFRAME:

<iframe src="/manager/" id="cabinetz" name="myframe" frameborder="0" width="100%" scrolling="no"></iframe>

The form within IFRAME has id " myform ".

How can I modify the json part to submit both forms at the same time?

Not tested, but try setting up a button with a class, setup submit handlers for each form, then fire $.submit() on both forms.

<button class="do-forms">Submit</button>

$( ".do-forms" ).click(function() {

  $("#loginForm").submit(function() { 
   // do ajax call 
  });

  $("#myform").submit(function() { 
   // do ajax call 
  });

  $( "#loginForm" ).submit();
  $( "#myform" ).submit();

});

Create button and give it ID

Jquery Code

$(document).ready(function () {
    $('#loginForm').ajaxForm({
        dataType: 'json',
        success: function (data) {
            if (data.success) {
                window.location.replace("/cabinet/");
            } else {
                $('#login-error').delay(500).fadeIn('slow').html(data.errors.login);
                $('#login-error').delay(2500).fadeOut('slow');
            }
        }
    });

    //ajax form method for second form 

    $('#myform').ajaxForm(function () {
        alert("second form reponse");
    });

    //click event for submitting both form

    $("#testbutton").on('click', function () {
        $('#loginForm').submit();
        $('#myform').submit();
    });
});

Here is a Demo for same situation but without iframe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM