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
Solution 1:
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!
Solution 2:
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();
}
});
Solution 3:
Why dont just create a form with some hidden inputs and submit it using jQuery? Should work :)
Solution 4:
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 .