I've queried and doesn't work out what I've found. Is there any way to redirect to give url with POST method using Javascript or jquery?
in response to a POST request. Rather, the RFC simply states that the browser should alert the user and present an option to proceed or to cancel without reposting data to the new location. Unless you write complex server code, you can't force POST redirection and preserve posted data.
Based on Eugene Naydenov's answer, I ended up using this which is able to fill form data also, hope to be useful for others:
function redirectPost(url, data) { var form = document.createElement('form'); document.body.appendChild(form); form.method = 'post'; form.action = url; for (var name in data) { var input = document.createElement('input'); input.type = 'hidden'; input.name = name; input.value = data[name]; form.appendChild(input); } form.submit(); } // redirectPost('http://www.example.com', { text: 'text\n\ntext' });
Update (2021): Some years later turned out a version that opens a new tab/window also would be useful for me so hopefully this would be useful also, just that make sure this will happen in a click event as browsers should block that otherwise,
function openPostPage(url, data) { var form = document.createElement('form'); document.body.appendChild(form); form.target = '_blank'; form.method = 'post'; form.action = url; for (var name in data) { var input = document.createElement('input'); input.type = 'hidden'; input.name = name; input.value = data[name]; form.appendChild(input); } form.submit(); document.body.removeChild(form); }
Create a form, fill method
and action
attributes, submit the form.
var redirect = function(url, method) { var form = document.createElement('form'); form.method = method; form.action = url; form.submit(); }; redirect('http://www.example.com', 'post');
jQuery version (but I'd prefer pure JavaScript in this particular case):
var redirect = function(url, method) { $('<form>', { method: method, action: url }).submit(); }; redirect('http://www.example.com', 'post');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With