32

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?

alex.b
  • 168
  • 14
Satheesh
  • 399
  • 2
  • 5
  • 11

11 Answers11

63

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);
}
Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81
  • 4
    This is the best answer as it accounts for sending data via the POST method, which is why you would want to use a POST method redirection, or else you'd use GET. – Deanie Sep 03 '17 at 17:44
  • 2
    You might have to add `document.body.appendChild(form);` to this (for example just before `form.submit()`), because the HTML spec doesn't allow forms that are not associated with the document to be submitted. See [this answer](https://stackoverflow.com/a/42081856) for more information. – Pascal Sommer Dec 02 '17 at 20:18
  • 1
    I would suggest also adding `document.body.removeChild(form);` after the submit. – ruben056 Jan 23 '18 at 09:15
  • 1
    I'm glad I found this SO post and answer. Using `XMLHttpRequest` to redirect a page from other domain wouldn't allow. Browser will detect it with no `Access-Control-Allow-Origin`, this is one way to solve `CORS` issue using a form submit to redirect a post request. – Junius Mar 28 '19 at 21:40
  • 1
    @ruben056 We redirecting the currently displayed page away. Everything will be removed anyway. – Daniel Wu Aug 07 '20 at 03:03
19

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');
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
  • This won't work if the method is a different domain. However if you insert it into the document it will work. – scruffian Mar 13 '15 at 15:21
  • 4
    Of course. Same as with any form submit. Just because of [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). – Eugene Naydenov Mar 13 '15 at 19:08
  • I had to add this to let the submit works: $('body').append(form); – NiBE Nov 08 '17 at 11:40
10

Here the idea is to send data to server while you redirect user to another webpage without using the GET method and maintaining a cosmetic appearance to your URL. So we are going to use the same procedure of sending a Form with POST method.

HTML/Javascript code for creating the form and submitting it to server:

<html>
<body>
<script>
var form = document.createElement("form");
form.method = 'post';
form.action = 'receive.php';
var input = document.createElement('input');
input.type = "text";
input.name = "data";
input.value = "this is the data I'm sending to server through POST";
form.appendChild(input);
form.submit();
</script>
<body>
<html>

Receiving this data in PHP:

<pre>
<?php
var_dump($_POST);
?>
</pre>

In this way, users will be redirected to receive.php with some data being informed in a POST method.

Fernando
  • 1,477
  • 2
  • 14
  • 33
2

Actually there is a trick. You create a hidden form and trigger the submit button, with jQuery for example:

<form method="POST" action="newurl.html" id="myform">
</form>

and do a

$('#myform').submit();

I suggest you to use the no-jQuery version posted by Eugene Naydenov

Sergey Telshevsky
  • 12,077
  • 6
  • 55
  • 78
  • 1
    Note that this doesn't require jQuery if you change `$('#myform').submit()` to `document.querySelector('#myform').submit()`. – anyweez Dec 03 '16 at 22:17
2

Try this:

var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
  '<input type="text" name="api_url" value="' + Return_URL + '" />' +
  '</form>');
$('body').append(form);
$(form).submit();
Guru
  • 621
  • 1
  • 4
  • 12
2

Redirect with POST vars (on jQuery)

var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});
sohel shaikh
  • 102
  • 1
  • 12
-2

You can use serialize your form and all the data in post. Below is an example.

$("#submit_btn").click(function(){
        $('.error_status').html();
            if($("form#frm_message_board").valid())
            {
                $.ajax({
                      type: "POST",
                      url: "<?php echo site_url('message_board/add');?>",
                      data: $('#frm_message_board').serialize(),
                      success: function(msg) {
                          var msg = $.parseJSON(msg);
                          if(msg.success=='yes')
                          {
                                                                            return true;
                         }
                         else
                         {
                            alert('Server error');
                            return false;
                        }
                       }
                });
            }
            return false;
        });
-3

There is no way to do so.

Even a a element Sstrikes the GET.

What you can do is make a Ajax request to post and in on-success use window.open().

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
-3

I think you should construct and fill out a hidden method=POST action="YOUR_URL" form and submit it,

renacimiento
  • 142
  • 1
  • 9
-3

Using jQuery post the data and redirect to your desired location like so:

$.ajax({
  type: 'POST',
  url: 'receivedata.asp',
  data: 'formValue=someValue',
  success: function(data){
      window.location = data;
  }
});

You could remove the data: 'formValue=someValue', if there is no data to pass to the page you want to post to.

arpan desai
  • 889
  • 2
  • 13
  • 23
-4

huh... use AJAX Jquery:

> $.ajax({
>                       type: "POST",
>                       url: "www.example.com/the_page_I_post_to.php",
>                       data: $('yourform').serialize(),//sent data
>                       success: function(msg) {
>                           alert("posted !");
>                        }
3pic
  • 1,188
  • 8
  • 26
  • 1
    JQuery $.ajax does not actually redirect. It sends a XHR in the background. Answer posted by @Fernando works best according to what was asked. – Binaek Sarkar Oct 04 '15 at 08:31