237

Basically what I want to do is send POST data when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can’t simply place it in the URL as a GET for cosmetic reasons.

This is what I have at the moment, but it doesn’t send any POST data.

if(user has not voted) {

    window.location = 'http://example.com/vote/' + Username;

}

I know that you can send POST data with jQuery.post(), but I need it to be sent with the new window.location.

So to recap, I need to send api_url value via POST to http://example.com/vote/, while sending the user to the same page at the same time.


For future reference, I ended up doing the following:

if(user has not voted) {

    $('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');

    document.forms['vote'].submit();

}
Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
Josh Foskett
  • 3,817
  • 5
  • 30
  • 35

11 Answers11

237

per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..

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();
Adi
  • 4,989
  • 6
  • 30
  • 47
tardate
  • 15,050
  • 14
  • 48
  • 49
  • 8
    I prefer this method over Kevin's method because you don't have to add a form to the html. The reason I wanted to do this was that I had a form already and nested another form inside of it. For some reason my main form decided to stop where the other began, ignoring all of the inputs that followed. I know this shouldn't happen, but there you go. The above method is nice when you want to 'redirect' with POST data from a piece of JS. Although I can't really shake feeling dirty when I do it this way ;). – Mosselman Oct 26 '12 at 08:48
  • 4
    Note that `$(form)` on the last line is redundant. – Joe May 10 '13 at 15:40
  • 8
    Just to add, current approach would display form for a fraction of a second on the "UI" before submitting. Just to make it perfect, add 'style' attribute to the form tag with value 'display: none;' . – Rohan Karwa Aug 15 '13 at 23:56
  • 7
    As long as there's no style on the form element (borders, margins and whatnot) you can use `type="hidden"` instead. – Big McLargeHuge Nov 25 '13 at 19:01
  • 1
    @Joe Depends how the method is called. If called via a hyperlink instead of a submit button `$(form).submit();` is very valid. However `$('body').append(form);` is redundant as the variable `form` is being submitted. – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ May 20 '14 at 09:45
  • It's what I needed in few rows of code :D thank you!! – Bellots May 23 '14 at 14:21
  • 3
    I found that $('body').append(form); was very necessary in IE browsers! – Thomas Jun 27 '14 at 09:12
  • 3
    @MatthewT.Baker I mean var form = $(...) gives you a jQuery instance. You don't need to re-wrap it in $(). form.submit() is enough. – Joe Jul 02 '14 at 19:02
  • @Mosselman, I felt the same way. Worked like a charm, but same dirty feeling. Would be nice if there was an ajax call that mimicked a form being submitted. – ghukill Oct 08 '14 at 20:24
  • ugly but useful, thx. Better avoid – ssj Nov 13 '14 at 10:21
  • I am unable to access this form in a spring controller to which the form is posted. Any clue of how can I get the form contents? Please. – swateek Feb 19 '15 at 18:53
  • Yuck. Super wish this was just in jQuery core. – Anthony Nov 22 '15 at 23:27
  • you are my saviour, thanx a lot – troy_achilies May 16 '17 at 11:19
184

Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.

Kevin Reid
  • 21,218
  • 9
  • 61
  • 82
  • 4
    Is there any way to do this using an nested object? Say I need the data `{"a":{"b":"c"}}` passed along. Is there a way to that with a form? – Aakil Fernandes Nov 24 '14 at 21:45
  • 7
    @AakilFernandes You can always `JSON.stringify` your object and put the resulting string into a form field. You **can't** send an arbitrary POST content type that a form wouldn't otherwise support. – Kevin Reid Nov 24 '14 at 22:05
  • but what if there is a `
    ` already? what can be done since `form` tags cannot be nested??
    – Malcolm Salvador Jul 04 '17 at 07:44
  • 2
    @Malky.Kid do it as you would normally with a form, for example _(using @AakilFernandes' data)_ you'd create `` within the form where "b" is a property of "a" with value "c". – Adam Whitney Aug 06 '17 at 14:27
58

Here's a simple small function that can be applied anywhere as long as you're using jQuery.

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

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            value = value.split('"').join('\"')
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
    }
});
therealrootuser
  • 7,249
  • 6
  • 27
  • 43
tfont
  • 9,576
  • 4
  • 48
  • 51
32

Here is a method, which does not use jQuery. I used it to create a bookmarklet, which checks the current page on w3-html-validator.

var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

document.body.appendChild(f);
f.submit();
olee
  • 626
  • 5
  • 12
32

If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.

Ola
  • 915
  • 8
  • 6
Tom Sarduy
  • 16,482
  • 8
  • 64
  • 83
  • This plugin worked great for me, thanks. I just copied and pasted the whole class into my code and use the example you have to test it and it worked fine. Now to include it properly... – OG Sean Jul 09 '18 at 00:12
17

The answers here can be confusing so i will give you a sample code that i am working with.

To start with note that there is no POST parameter to java script windows.location function that you are referring to.

So you have to...

  1. Dynamically make a form with a POST parameter.

  2. Dynamically put a textbox or textboxes with your desired values to post

  3. Invoke the submit form you dynamically created.

And for the example.

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.

On test2.php you can get your values thus.

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

Amaan Iqbal
  • 733
  • 2
  • 9
  • 23
webs
  • 445
  • 4
  • 9
16

Generic function to post any JavaScript object to the given URL.

function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}
therealrootuser
  • 7,249
  • 6
  • 27
  • 43
7

This is quite handy to use:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

myRedirect("/yourRedirectingUrl", "arg", "argValue");
Sayed Ali
  • 71
  • 1
  • 4
1
var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/

Going to try this and other suggestions for my work.

Is there any other way to do the same ?

Rajesh
  • 11
  • 1
0

You can use target attribute to send form with redirect from iframe. Your form open tag would be something like this:

method="post" action="http://some.url.com/form_action" target="_top"
joni jones
  • 2,437
  • 2
  • 20
  • 27
-13

SOLUTION NO. 1

 //your variable
    var data = "brightcherry";

    //passing the variable into the window.location URL
    window.location.replace("/newpage/page.php?id='"+product_id+"'");

SOLUTION NO. 2

//your variable
var data = "brightcherry";

//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);

details

Mohammad Faizan khan
  • 1,177
  • 3
  • 13
  • 32