Can a HTML button perform a POST request?
Yes, an HTML button can indeed perform a POST request by placing it inside a <form>
that uses method="post"
. Specify the destination with the action
attribute:
Click the button to POST to the specified URL. Use <input>
elements to add data.
How does it work? Invisible elves or...?
Contained within a form, a button with type="submit"
becomes the all-powerful trigger of submission. Upon clicking, any <input>
elements with name
attributes within the form will be included in the POST request's payload:
The name
attribute is like the elf whisperer, ensuring the server knows who sent which present. This <input>
hides the elves (data) from the user while ferrying them to the server.
Flexing your button swag
The label of a button is as cosmetic as a unicorn's hairstyle. Use the value
attribute to define the real magic:
Here, "Fluffy Tails!" is for the user's satisfaction, while the "unicorn_magic" is the real payload.
Rogue buttons outside form borders
Buttons lurking outside a <form>
can kick off form submissions too! They use the form
attribute referencing the ID of the form:
On clicking, the button summons the form with ID rogueForm
.
Was this article helpful?