Send POST data on redirect with JavaScript/jQuery?

Josh Foskett picture Josh Foskett · Dec 5, 2011 · Viewed 411.3k times · Source

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();

}

Answer

tardate picture tardate · Apr 5, 2012

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();