jQuery - Redirect with post data
Asked Answered
S

13

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

Sled answered 26/9, 2013 at 19:12 Comment(4)
I am actually very interested to hear this answer.Prussiate
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.Freddiefreddy
Are you forgetting the PHP tag, or does jQuery have a $_POST variable?Flycatcher
@y2k, Isn't this the same question as https://mcmap.net/q/45910/-send-post-data-on-redirect-with-javascript-jquery-duplicate/632951 ?Arrestment
D
94

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'});
Doodlebug answered 26/9, 2013 at 19:26 Comment(9)
@TimS, after checking out that link, I am still unclear as to how you can retrieve the data in the new page using post.Cogen
nevermind, I figured it out and got it to work. Great suggestion!Cogen
<script type="text/javascript"> $().redirect('localhost:8080/vabc/index.php#data/t.php?param=12&edit=2', {'e': 'error'}); Doesn`t work. I also have a <form> with some other post variables which first post to the same page and after processing, I use jquery redirect to redirect to a different page with some new post variables.Ectomorph
Using jquery 2.1.3 and the correct syntax for me was $.redirect(...); Without the parenthesis.Arron
So we can`t redirect to a different url and post to a different one>?Ectomorph
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.Quackery
andyh0316 or slightly larger chunks of datat that would not safely fit in a get urlPindaric
How can someone add headers to the post request?Ari
How can i use this in react js?Ari
F
95

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();
    }
});
Fess answered 28/4, 2014 at 17:45 Comment(4)
add .appendTo('body') for mobile devices... example: $('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit(); idea based on this answerBiodynamics
This solution is much better than the accepted answer imo. It's easy to implement and no need for loading additional libraries!Mcguigan
I get $.redirectPost is not a function error when trying to use this.Armillda
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: https://mcmap.net/q/45092/-javascript-post-request-like-a-form-submitCorvine
D
94

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'});
Doodlebug answered 26/9, 2013 at 19:26 Comment(9)
@TimS, after checking out that link, I am still unclear as to how you can retrieve the data in the new page using post.Cogen
nevermind, I figured it out and got it to work. Great suggestion!Cogen
<script type="text/javascript"> $().redirect('localhost:8080/vabc/index.php#data/t.php?param=12&edit=2', {'e': 'error'}); Doesn`t work. I also have a <form> with some other post variables which first post to the same page and after processing, I use jquery redirect to redirect to a different page with some new post variables.Ectomorph
Using jquery 2.1.3 and the correct syntax for me was $.redirect(...); Without the parenthesis.Arron
So we can`t redirect to a different url and post to a different one>?Ectomorph
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.Quackery
andyh0316 or slightly larger chunks of datat that would not safely fit in a get urlPindaric
How can someone add headers to the post request?Ari
How can i use this in react js?Ari
S
8

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

Scarlettscarp answered 26/9, 2013 at 19:18 Comment(3)
Won't work with drag'n'drop file uploads. You can't assign file input for security reasons.Twist
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.Scarlettscarp
@Twist 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.Blather
I
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

Incorruptible answered 24/1, 2019 at 21:26 Comment(0)
U
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 .

Underproduction answered 16/2, 2015 at 0:9 Comment(0)
B
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 !

Blubber answered 9/6, 2015 at 11:33 Comment(0)
B
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.

Broadway answered 26/9, 2013 at 21:56 Comment(0)
M
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();
    }
});
Macaco answered 27/4, 2017 at 14:0 Comment(1)
This method does not support arrays used as values, while the accepted answer using jquery redirect plugin doesHotchpot
V
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);
});
Valetudinary answered 26/9, 2013 at 21:13 Comment(1)
This will just cause a normal GET request as the url is changing. The original question was to make POST request.Workhouse
A
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();
    });
Ambrosio answered 23/10, 2013 at 7:14 Comment(1)
Note: Inputs should be input Ids NOT names!Ambrosio
I
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();
Inventive answered 1/7, 2014 at 15:24 Comment(0)
D
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();
       }
   });
Dialogist answered 28/2, 2019 at 6:10 Comment(0)
A
-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");
Afrit answered 20/5, 2023 at 8:36 Comment(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.Valentino

© 2022 - 2024 — McMap. All rights reserved.