Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Sending POST, redirecting to response

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?

like image 290
JamesBrownIsDead Avatar asked Feb 08 '10 19:02

JamesBrownIsDead


People also ask

Can a POST request be redirected?

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.

How do I redirect a response?

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.

What is response redirect JavaScript?

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.


1 Answers

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);
});
like image 118
cgarciagl Avatar answered Nov 01 '22 15:11

cgarciagl