How to simulate form submission with POST request using JavaScript?

Hey everyone! I’m stuck on something and could use some help. I want to send a POST request to a website and have the browser go to a new page, just like when you submit a form. I know how to do a GET request with JavaScript, but POST is giving me trouble.

I tried using document.location.href, but that only works for GET requests. I also thought about creating a hidden form and submitting it, but I’d rather do this all with JavaScript if possible.

What I’m looking for is a way to do something like this:

sendPostRequest('https://somewebsite.com', {data: 'example'});

This should work in all browsers and actually change the page, not just send data in the background. I don’t want to use AJAX or anything async.

Does anyone know how to do this? I’ve been scratching my head for hours! Thanks in advance for any help!

I understand your desire to stick with pure JavaScript, but sometimes the simplest solution is the most effective. Have you considered using the Fetch API? It’s widely supported and can handle POST requests elegantly. Here’s a straightforward approach:

function sendPostRequest(url, data) {
    const form = new FormData();
    for (let key in data) {
        form.append(key, data[key]);
    }
    
    fetch(url, {
        method: 'POST',
        body: form
    }).then(response => {
        window.location.href = response.url;
    });
}

This method sends a POST request and then redirects to the response URL, mimicking a form submission. It’s clean, modern, and works in all major browsers. Just be aware it’s asynchronous by nature, so the page won’t change instantly.

yo mike, try using fetch with a post and then redirect via window.location.assign().

fetch(url, { method:‘POST’, body: JSON.stringify(data) }).then(() => window.location.assign(url));

works fine in modern browsers.

I’ve actually dealt with this exact issue before in a project. The cleanest solution I found was to dynamically create and submit a form element. Here’s a function I’ve used successfully:

function sendPostRequest(url, params) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = url;
    
    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];
            form.appendChild(hiddenField);
        }
    }
    
    document.body.appendChild(form);
    form.submit();
}

This approach works across browsers and actually navigates to a new page, just like a regular form submission. It’s not as neat as your ideal syntax, but it gets the job done without relying on AJAX or other async methods. Hope this helps!