Javascript post request like a form submit
Here, we create a function to mimic a form submission using a POST request in JavaScript.
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
.
Joining the DOM party
Always remember to append the form to the document body to make it feel at home.
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()
:
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.
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.
Was this article helpful?