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
Answer: Use the JavaScript window. location Propertylocation property to make a page redirect, you don't need any jQuery for this. If you want to redirect the user from one page to another automatically, you can use the syntax window. location. replace("page_url") .
Using window. location. href it's not possible to send a POST request. What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.
$. ajax({ type: 'POST', url: 'AJAX URL', data: "YOUR DATA" // don't forget to pass your csrf_token when using post success: function(data){ $("what_ever_you_want_to_replace"). html(data. view); }, error: function(xhr, type, exception) { // if ajax fails display error alert alert("ajax error response type "+type); } });
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!
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(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With