Skip to content

Instantly share code, notes, and snippets.

@cgarciagl
Last active November 30, 2023 17:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgarciagl/3744034 to your computer and use it in GitHub Desktop.
Save cgarciagl/3744034 to your computer and use it in GitHub Desktop.
function to redirect a webpage to another using post method
function redirectByPost(url, parameters, inNewTab) {
parameters = parameters || {};
inNewTab = inNewTab === undefined ? true : inNewTab;
var form = document.createElement("form");
form.id = "reg-form";
form.name = "reg-form";
form.action = url;
form.method = "post";
form.enctype = "multipart/form-data";
if (inNewTab) {
form.target = "_blank";
}
Object.keys(parameters).forEach(function (key) {
var input = document.createElement("input");
input.type = "text";
input.name = key;
input.value = parameters[key];
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
}
@Alynva
Copy link

Alynva commented Sep 10, 2021

Do not use raw HTML at line 12. Instead, create the input element and set its value programmatically:

const input = document.createElement('input')
input.name = key
input.value = pparameters[key]
form.appendChild(input)

Using raw HTML do not work with " and line breaks

@cgarciagl
Copy link
Author

Thank you, now the function has been improved, and the dependency on JQuery has been removed. 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment