Submit a Dynamically Generated Form with jQuery
A dynamically generated form is useful when a page must perform a normal browser navigation with a POST request, such as exporting a file with parameters. This avoids keeping a hidden form in the page markup.
Use DOM APIs to assign field values. Do not concatenate untrusted data into HTML strings, because that can break the markup or introduce an injection vulnerability.
The following legacy example creates a form, appends it to the document, submits it, and then removes it:
var result = $("#printDIV").html();
var xlsName = "excel-file";
var url = "exportExcel/export";
var form = $("<form></form>");
form.attr("action", url);
form.attr("method", "post");
form.append($("<textarea></textarea>").attr("name", "result").val(result));
form.append($("<textarea></textarea>").attr("name", "xlsName").val(xlsName));
form.appendTo("body").trigger("submit");
form.remove();
Appending the form to body is important for compatibility with older browsers and ensures that the form participates in the document before submission.
Modern JavaScript version
jQuery is not required for this pattern:
function postNavigate(url, values) {
const form = document.createElement("form");
form.method = "post";
form.action = url;
for (const [name, value] of Object.entries(values)) {
const input = document.createElement("input");
input.type = "hidden";
input.name = name;
input.value = String(value);
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
form.remove();
}
postNavigate("exportExcel/export", {
result: document.querySelector("#printDIV").innerHTML,
xlsName: "excel-file"
});
For ordinary API calls that do not require a full-page navigation or native download flow, use fetch() instead.