How to send POST data and redirect browser using JavaScript

I need to redirect my browser to another page using POST method instead of GET.

For GET requests, I can simply use:

window.location.href = 'https://mysite.com/search?term=hello';

But the API I’m working with only accepts POST requests. If I was using static HTML, I could create a form like this:

<form action="https://mysite.com/api" method="POST">
    <input type="hidden" name="search" value="hello">
    <input type="submit" value="Go">
</form>

However, I want to do this programmatically with JavaScript. Ideally, I’d like a function that works like:

sendPostRequest('https://mysite.com/api', {'search': 'hello'});

What’s the most reliable way to implement this across different browsers? I need the browser to actually navigate to the new page after sending the POST data, similar to how a form submission works. AJAX won’t work here because I need the page to redirect, not just send data in the background.

just make a form on the fly, right? use document.createElement to build it, then throw your inputs in there. attach it to the body, and boom, call submit()! like this: let form = document.createElement('form'); form.method = 'POST'; form.action = url; then add your data and just form.submit(). easy peasy.

Been dealing with this for years - dynamic form creation works great. Just watch out for servers that expect specific content types or have CSRF protection. I always wrap form creation in try-catch since submissions can fail silently when servers reject requests. Popup blockers and security settings sometimes block programmatic submissions too, especially if they’re not from direct user clicks. In production, I add a small setTimeout delay before calling submit() so the DOM finishes processing the form. This approach has worked across different projects and browsers.

The dynamic form approach works, but here’s a cleaner way to handle it. I use this reusable function that generates form elements programmatically and handles cleanup automatically:

function postRedirect(url, data) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = url;
    form.style.display = 'none';
    
    Object.keys(data).forEach(key => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    });
    
    document.body.appendChild(form);
    form.submit();
}

Works with older browsers and doesn’t need external libraries. I’ve tested it on IE11, Chrome, Firefox and Safari - no issues. Main advantage is it behaves exactly like a traditional form submission, keeping the POST method while redirecting properly.