I have an image with an onclick. When the click event fires, I want to send an HTTP POST and have the window.location redirect to the response to the POST. How can I do that?
Some browsers mitigate this risk by warning the user that they are about to re-issue a POST request. To avoid this problem, many web developers use the PRG pattern—instead of responding with content, the server responds to a POST request by redirecting the client to another location.
In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3 , and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header.
redirect() The redirect() method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired.
You could use this function i made:
function redirect_by_post(purl, pparameters, in_new_tab) {
pparameters = (typeof pparameters == 'undefined') ? {} : pparameters;
in_new_tab = (typeof in_new_tab == 'undefined') ? true : in_new_tab;
var form = document.createElement("form");
$(form).attr("id", "reg-form").attr("name", "reg-form").attr("action", purl).attr("method", "post").attr("enctype", "multipart/form-data");
if (in_new_tab) {
$(form).attr("target", "_blank");
}
$.each(pparameters, function(key) {
$(form).append('<input type="text" name="' + key + '" value="' + this + '" />');
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
}
$('#btn').button().click(function() {
redirect_by_post('http://pamppi.info/jotform-testing/thankyou/postvars.php', {
variable1: 'Carlos',
variable2: 'Garcia'
}, true);
});
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