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, i.e. 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 (i.e. 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, 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:
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.