Skip to content

Instantly share code, notes, and snippets.

@cgarciagl
Last active January 15, 2025 19:44
Show Gist options
  • 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
/**
* Redirige mediante un formulario POST.
*
* @param {string} url - La URL a la que se redirige.
* @param {Object} [parameters={}] - Los parámetros que se enviarán como datos POST.
* @param {boolean} [inNewTab=true] - Si se debe abrir en una nueva pestaña.
* @returns {void}
*/
function redirectByPost(url, parameters = {}, inNewTab = true) {
// Validación básica de la URL
if (!url || typeof url !== "string") {
throw new Error("El parámetro 'url' debe ser una cadena no vacía.");
}
// Crear el formulario dinámicamente
const form = document.createElement("form");
form.id = "redirect-form";
form.name = "redirect-form";
form.action = url;
form.method = "post";
form.enctype = "multipart/form-data";
// Abrir en nueva pestaña si se especifica
if (inNewTab) {
form.target = "_blank";
}
// Agregar los parámetros como campos ocultos
for (const [key, value] of Object.entries(parameters)) {
const input = document.createElement("input");
input.type = "hidden"; // Usar campos ocultos para evitar interferencias visuales
input.name = key;
input.value = value !== null && value !== undefined ? value : ""; // Manejo de valores nulos/indefinidos
form.appendChild(input);
}
// Insertar el formulario al DOM, enviarlo y luego eliminarlo
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
@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