Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect through 'POST' method using Javascript?

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?

like image 376
Satheesh Avatar asked Sep 28 '13 07:09

Satheesh


People also ask

Can we redirect with POST?

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.


2 Answers

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); } 
like image 87
Ebrahim Byagowi Avatar answered Oct 05 '22 23:10

Ebrahim Byagowi


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'); 
like image 43
Eugene Naydenov Avatar answered Oct 06 '22 01:10

Eugene Naydenov