massimo
massimo

Reputation: 21

Ajax redirect using POST

He have seen a lot of answers on how to redirect to a different page after a successful Ajax call, but all of them uses a GET method. I'd like, instead, to pass my parameters to the new page using the POST method. How can i do it?

Upvotes: 2

Views: 3714

Answers (2)

Pushkar
Pushkar

Reputation: 7580

Well i have faced this issue before and the only way to do this seems(maybe i am wrong) to be by defining a AJAX success callback function and redirect from that callback function. If you want you can send back the redirect url itself in the AJAX response and read the redirect URL in the call back function.

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 237817

You can't programmatically set the browser to do a POST request, only an XMLHTTPRequest one. The best you can do is simulate it by creating a new form element with the data you want to submit, then calling submit on it:

var params = {name: 'lonesomeday', website: 'stackoverflow'};

var form = document.createElement('form');
form.action = 'http://example.com';
form.method = 'post';

for (var key in params) {
    if (params.hasOwnProperty(key) {
        var field = document.createElement('input');
        field.type = 'hidden';
        field.name = key;
        field.value = params[key]

        form.appendChild(field);
    }
}

document.body.appendChild(form);
form.submit();

Upvotes: 1

Related Questions