简体   繁体   中英

jQuery - submit multiple forms through single request, without Ajax

I have a page with several forms. I am trying to submit one of the forms (say form A) (NOT through Ajax, since I need to load the result page after the submit is processed), BUT I need another form's contents (say form B) to be submitted TOGETHER with form A, ie the contents of forms A + B should be submitted TOGETHER to the SAME URL, as one request, and as I said before, NOT as an Ajax request.

The submit should be by a POST request. Also, the forms contain ONLY fields that are not file upload (ie input, select, textarea fields).

I have seen suggestions here such as

Posting/submitting multiple forms in jQuery

or

Submitting two forms with a single button

but pay attention that these do not match my case, since the forms are submitted in different requests, and/or they are submitted through Ajax.

I was thinking of getting the contents of one of the forms by (the jQuery's) serialize(), but how do I attach that string to a form submitted by POST?

Or maybe you have other ideas how to accomplish this?

SOLUTION:

Based on the ideas of Sheepy and YoTsumi, I wrote the following code. I am also using the answer by Pointy from the following link:

submit multiple forms to same page

//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
    var forms = [];
    $.each($.makeArray(arguments), function(index, value) {
        forms[index] = document.forms[value];
    });
    var targetForm = forms[0];
    $.each(forms, function(i, f) {
        if (i != 0) {
            $(f).find('input, select, textarea')
                .hide()
                .appendTo($(targetForm));
        }
    });
    $(targetForm).submit();
}

Well, you have to copy the data from form2 to form1 before the submit. Here is the basic to get you started:

$.each ( $('#form2 input, #form2 select, #form2 textarea').serializeArray(), function ( i, obj ) {
  $('<input type="hidden">').prop( obj ).appendTo( $('#form1') );
} );

This function would select inputs from form2, get their current values, then create a new hidden input for each of them and add them to form1.

Depending on your scenario you may want to check the existance of input with same name on form1 first.

A solution to inject the data directly in the post request (and not in a sub field)

<form id="form1">
    <input ... />
    <input ... />
</form>

<form id="form2">
    <input ... />
    <input ... />
</form>

<form id="result" action="..." method="POST" onsubmit="merge(); return true;">
    <input type="submit" />
</form>


<script type="text/javascript">
    function merge() {
        $result = $("#result");
        $("#form1 input, #form2 input, #form1 select, #form2 select, #form1 textarea, #form2 textarea").each(function() {
            $result.append("<input type='hidden' name='"+$(this).attr('name')+"' value='"+$(this).val()+"' />");
        });
    }
</script>

You can only do one request at a time and that will reload the page unless you use AJAX. The only other option would be to create a script which concatantes the seralizations of your two forms - but at that point, why wouldn't you just use one large form..

Edit: For your combining the two forms, there is an example of this in the answer of the second link you provided.

form A:

<form method="post" action="next.html" onsubmit="this.formbVal.value = $('#formb').serialize(); return true;">
    <input type="hidden" name="formbVal" value="" />
    <input type="submit">
</form>

form B:

<form id="formb" method="post" action="#" onsubmit="return false;">
</form>

I discovered that your solution will copy the form to another invissible form, but the backside is that the original forms will be cleared an such edit of the original form (eg after form validation errors) is not possible.

To solve this i tried to clone the elements before appending it to the invissible form. I edited your code like this:

//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")    
function mergeForms() {
        var forms = [];
        $.each($.makeArray(arguments), function(index, value) {
            forms[index] = document.forms[value];
        });
        var targetForm = forms[0];
        $.each(forms, function(i, f) {
            if (i != 0) {
                $(f).find('input, select, textarea')
                    .clone()
                    .hide()
                    .appendTo($(targetForm));
            }
        });

Unfortunatly now it doesn't copy the selected values in a select element.

Hope someone can help me to impove this script

you can do some thing like this

$('#SubmitBtn).click(function () {
        $("#formId").attr("action", "http://www.YourSite.com/");
        $("#formId").attr("method", "post");
        $("#formId").attr("target","_blank");
        $('#formId').submit();
    });

this will submit the for to http://www.YourSite.com/ in a new window

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