Last active
January 15, 2025 19:44
-
-
Save cgarciagl/3744034 to your computer and use it in GitHub Desktop.
function to redirect a webpage to another using post method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
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
Do not use raw HTML at line 12. Instead, create the input element and set its value programmatically:
Using raw HTML do not work with " and line breaks