[javascript] jQuery - Redirect with post data

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

This question is related to javascript jquery html post

The answer is


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'});

Hope this helps!


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

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

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 .


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

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 !


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.


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


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


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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time