87

How can I redirect with post data?

How to move to new page with $_POST?

How to do this? How is it done and whyfore shall it be done

y2k
  • 65,388
  • 27
  • 61
  • 86
  • 6
    I am actually very interested to hear this answer. – Sterling Archer Sep 26 '13 at 19:15
  • 2
    It's not possible to set the windows location with a POST request, only GET requests, and it's not possible to redirect a POST request, so the usual solution is to dynamically create a form with the needed data and action attribute, and submit it. – adeneo Sep 26 '13 at 19:21
  • Are you forgetting the PHP tag, or does jQuery have a `$_POST` variable? – Alex W Sep 26 '13 at 19:23
  • @y2k, Isn't this the **same** question as http://stackoverflow.com/q/8389646/632951 ? – Pacerier Oct 03 '15 at 14:31

13 Answers13

94

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 ) {
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
    }
});

Per the comments, I have expanded upon my answer:

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = $('<form></form>');
        form.attr("method", "post");
        form.attr("action", location);

        $.each( args, function( key, value ) {
            var field = $('<input></input>');

            field.attr("type", "hidden");
            field.attr("name", key);
            field.attr("value", value);

            form.append(field);
        });
        $(form).appendTo('body').submit();
    }
});
JimTheDev
  • 3,469
  • 1
  • 23
  • 26
tfont
  • 10,891
  • 7
  • 56
  • 52
  • 9
    add `.appendTo('body')` for mobile devices... example: `$('
    '+form+'
    ').appendTo('body').submit();` idea based on [this answer](http://stackoverflow.com/a/18870799)
    – CrandellWS Jun 25 '14 at 10:41
  • 4
    This solution is much better than the accepted answer imo. It's easy to implement and no need for loading additional libraries! – Matej Svajger Mar 09 '15 at 11:44
  • 3
    I get $.redirectPost is not a function error when trying to use this. – Rafiki Feb 22 '16 at 16:22
  • 1
    Great idea with extend. But this implementation does not escape values before putting them into `value=""` attribute. Thus if value contains quotes, it does not work. Function itself can be replaced with one that is aware about quoting, like from here: http://stackoverflow.com/a/5533477/1775065 – cronfy Mar 18 '16 at 10:25
93

There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.

After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:

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

Use the following code on newer JQuery versions instead:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
starball
  • 20,030
  • 7
  • 43
  • 238
Tim S
  • 2,309
  • 16
  • 23
  • @TimS, after checking out that link, I am still unclear as to how you can retrieve the data in the new page using post. – Yehuda Gutstein Nov 13 '13 at 07:02
  • nevermind, I figured it out and got it to work. Great suggestion! – Yehuda Gutstein Nov 13 '13 at 07:20
  • – TommyT May 08 '14 at 20:08
  • 19
    Using jquery 2.1.3 and the correct syntax for me was $.redirect(...); Without the parenthesis. – KDT Feb 18 '15 at 13:51
  • So we can`t redirect to a different url and post to a different one>? – TommyT Mar 20 '15 at 21:58
  • Doesn't work IF you want to use complex object (nested objects within object). The source code here only seems to work for flat object parameter. Which kinda defeats the purpose of POST because the advantage of POST vs GET is that POST lets you use complex parameter. – andyh0316 Jun 24 '16 at 20:07
  • andyh0316 or slightly larger chunks of datat that would not safely fit in a get url – Jeremy Apr 21 '17 at 19:53
  • How can someone add headers to the post request? – Jerry Okafor Jan 27 '19 at 23:14
  • How can i use this in react js? – Jerry Okafor Jan 28 '19 at 10:45
8

Why dont just create a form with some hidden inputs and submit it using jQuery? Should work :)

kao3991
  • 402
  • 2
  • 8
  • Won't work with drag'n'drop file uploads. You can't assign file input for security reasons. – mlt Nov 01 '16 at 00:45
  • I can't think of any situation when you may want to redirect user somewhere and make them upload a file with the same request. But of course - its true, it won't work in this case. – kao3991 Jan 31 '17 at 01:12
  • @mlt I'm not sure why it would not work. You don't assign anything to the file input, but you use other input hidden fields that are posted at the same time as your form. – Danosaure Aug 18 '17 at 14:01
4

This would redirect with posted data

$(function() {
       $('<form action="url.php" method="post"><input type="hidden" name="name" value="value1"></input></form>').appendTo('body').submit().remove();
    });

    }

the .submit() function does the submit to url automatically
the .remove() function kills the form after submitting

Tobiloba
  • 1,618
  • 1
  • 11
  • 7
3

Before document/window ready add "extend" to jQuery :

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {

            form += '<input type="hidden" name="'+value.name+'" value="'+value.value+'">';
            form += '<input type="hidden" name="'+key+'" value="'+value.value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});

Use :

$.redirectPost("someurl.com", $("#SomeForm").serializeArray());

Note : this method cant post files .

sagie212
  • 63
  • 6
3

I think this is the best way to do it !

<html>
<body onload="document.getElementById('redirectForm').submit()">
<form id='redirectForm' method='POST' action='/done.html'>
<input type='hidden' name='status' value='complete'/>
<input type='hidden' name='id' value='0u812'/>
<input type='submit' value='Please Click Here To Continue'/>
</form>
</body>
</html>

This will be almost instantaneous and user won't see anything !

Prashant Singh
  • 3,725
  • 12
  • 62
  • 106
1

This needs clarification. Is your server handling a POST that you want to redirect somewhere else? Or are you wanting to redirect a regulatr GET request to another page that is expecting a POST?

In either case what you can do is something like this:

var f = $('<form>');
$('<input>').attr('name', '...').attr('value', '...');
//after all fields are added
f.submit();

It's probably a good idea to make a link that says "click here if not automatically redirected" to deal with pop-up blockers.

LameCoder
  • 1,287
  • 7
  • 22
1

Similar to the above answer, but written differently.

$.extend(
{
    redirectPost: function (location, args) {
        var form = $('<form>', { action: location, method: 'post' });
        $.each(args,
            function (key, value) {
                $(form).append(
                    $('<input>', { type: 'hidden', name: key, value: value })
                );
            });
        $(form).appendTo('body').submit();
    }
});
Alan
  • 53
  • 6
0

why not just use a button instead of submit. clicking the button will let you construct a proper url for your browser to redirect to.

$("#button").click(function() {
   var url = 'site.com/process.php?';
   $('form input').each(function() {
       url += 'key=' + $(this).val() + "&";
   });
   // handle removal of last &.

   window.location.replace(url);
});
0

I included the jquery.redirect.min.js plugin in the head section together with this json solution to submit with data

<script type="text/javascript">     
    $(function () {
     $('form').on('submit', function(e) {
       $.ajax({
        type: 'post',
        url: 'your_POST_URL',
        data: $('form').serialize(),
        success: function () {
         // now redirect
         $().redirect('your_POST_URL', {
          'input1': $("value1").val(), 
          'input2': $("value2").val(),
      'input3': $("value3").val()
       });
      }
   });
   e.preventDefault();
 });
 });
 </script>

Then immediately after the form I added

 $(function(){
     $( '#your_form_Id' ).submit();
    });
0

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

or

$('#inset_form').html(
   '<form action="url" name="form" method="post" style="display:none;">
    <input type="text" name="name" value="' + value + '" /></form>');
document.forms['form'].submit();
Daniel Kennedy
  • 708
  • 11
  • 18
0

"extended" the above solution with target. For some reason i needed the possibility to redirect the post to _blank or another frame:

$.extend(
   {
       redirectPost: function(location, args, target = "_self")
       {
           var form = $('<form></form>');
           form.attr("method", "post");
           form.attr("action", location);
           form.attr("target", target);
           $.each( args, function( key, value ) {
               var field = $('<input></input>');
               field.attr("type", "hidden");
               field.attr("name", key);
               field.attr("value", value);
               form.append(field);
           });
           $(form).appendTo('body').submit();
       }
   });
ThoCra
  • 1
  • 1
-1

You can use jquery plugin called jquery redirect: https://github.com/mgalante/jquery.redirect

To redirect with post data passed and new page opened you can use syntax as the documentation has attach:

$.redirect("/your_url.php", {user: "johnDoe", password: "12345"}, "POST", "_blank");
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Void Code
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 20 '23 at 10:06