Explain Codes LogoExplain Codes Logo

Javascript post request like a form submit

javascript
vanilla-javascript
form-submission
async-operations
Alex KataevbyAlex KataevΒ·Jan 12, 2025
⚑TLDR

Here, we create a function to mimic a form submission using a POST request in JavaScript.

// Our "postal service" for delivering JavaScript "packages" const submitForm = (action, params) => { // Form creation β€” gotta have an envelope for our package, right? const form = Object.assign(document.createElement('form'), { action, method: 'POST' }); // Add hidden inputs β€” secret code for the delivery person (postman or axios maybe?) Object.entries(params).forEach(([name, value]) => { if (params.hasOwnProperty(name)) { form.appendChild(Object.assign(document.createElement('input'), { type: 'hidden', name, value })); } }); // Send it off πŸš€ document.body.appendChild(form).submit(); }; // Usage like a boss: submitForm('http://example.com/api', { key1: 'value1', key2: 'value2' });

I named the function submitForm. Put this function to work by feeding it the endpoint URL and an object holding the form data. Then, it will craft a form, populate hidden fields from the object, add it to the body, and submit the form.

The creative process: form crafting

In traditional HTML, form submissions are simple. Here's how to create a form programmatically and acquire absolute control over the requests.

Prepping for input creation

With this simple function, we create an input with 'name' and 'value' attributes matching our payload data, using good old document.createElement.

const createInput = (name, value) => { const input = document.createElement('input'); input.type = 'hidden'; input.name = name; input.value = value; return input; // Release the input into the wild! };

Joining the DOM party

Always remember to append the form to the document body to make it feel at home.

// Welcome to the document body! πŸŽ‰ document.body.appendChild(form);

Submitting in the clear

Try to avoid any form submission conflicts by ensuring the form is fully assembled and attached to the DOM before calling form.submit():

// shouting "Fire!" before aiming could be... unfortunate. form.submit();

Probably the safest route

Always validate

To eliminate any missteps, cross-check if a property truly belongs to an object before putting it to use.

if (params.hasOwnProperty(name)) { // Hidden data, move on, nothing to see here! 🧐 }

Works with all the cool browsers

This approach is like the best kind of party guest - one who fits in perfectly with any crowd. It's compatible with a vast range of browsers, including the old-school ones.

No need for external glitz

Why bother with external libraries like jQuery when you can achieve this in vanilla JavaScript? However, if you're one of jQuery’s fan club members, you could take advantage of the $.each and $('form').submit() functions.

Keeping it real

Nothing beats the real stuff; a traditional form submission. This method emulates a direct and immediate action triggered by the user, unlike XML or Ajax for their asynchronous operations.