How to redirect through ‘POST’ method using Javascript?

Based on Eugene Naydenov’s answer, I ended up using this which is able to fill form data also, hope to be useful for others:

function redirectPost(url, data) {
    var form = document.createElement('form');
    document.body.appendChild(form);
    form.method = 'post';
    form.action = url;
    for (var name in data) {
        var input = document.createElement('input');
        input.type="hidden";
        input.name = name;
        input.value = data[name];
        form.appendChild(input);
    }
    form.submit();
}

// redirectPost('http://www.example.com', { text: 'text\n\ntext' });

Update (2021): Some years later turned out a version that opens a new tab/window also would be useful for me so hopefully this would be useful also, just that make sure this will happen in a click event as browsers should block that otherwise,

function openPostPage(url, data) {
    var form = document.createElement('form');
    document.body.appendChild(form);
    form.target="_blank";
    form.method = 'post';
    form.action = url;
    for (var name in data) {
        var input = document.createElement('input');
        input.type="hidden";
        input.name = name;
        input.value = data[name];
        form.appendChild(input);
    }
    form.submit();
    document.body.removeChild(form);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)