I have two forms on one html page. Using jQuery, is it possible to have the data from both forms go into the POST data when the first is submitted?
Using serialize to combine forms and submit using ajax was working for me until I added an "export" button (to send data as an excel file). For that I needed to do a full postback. So I ended up with this method. It chooses the appropriate merge technique, and fixes some of the issues with buttons, selects and textareas along the way:
$("body").on("submit", ".combineForm", function () {
var frm = $(this);
var action = frm.attr("action");
var method = frm.attr("method");
var target = frm.data("updateTarget");
var combined = $(".combineForm");
//get the submit button that was clicked
var btn = $(this).find("button[type=submit]:focus");
var btnName = btn.attr("name");
var btnValue = btn.attr("value");
//create an in memory form to avoid changing the existing form
var f = $("")
//Browsers send the name and value of the clicked button but serialize, clone and our copy can't
//So add a hidden field to simulate browser behaviour
if (btnName)
f.append("")
if (btnValue === "export") {//exporting to a file needs full submit
//merge forms with class 'combineForm' by copying values into hidden inputs
// - cloning doesn't copy values of select or textareas
combined.find(":input").not("submit").each(function () {
var inp = $("")
f.append(inp);
});
f[0].submit();
return false;
}
//merge forms for ajax submit
var data = combined.serialize() + "&" + f.serialize();
$.ajax({
url: action,
type: 'POST',
data: data,
dataType: "html",
success: function (html) {
$(target).html(html);
}
});
return false;
});