Explain Codes LogoExplain Codes Logo

Can a HTML button perform a POST request?

html
form-submission
button-behavior
html-forms
Nikita BarsukovbyNikita Barsukov·Jan 15, 2025
TLDR

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:

<form action="http://example.com/endpoint" method="POST"> <button type="submit">Commence Posting</button> </form>

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:

<form action="/submit_or_regret" method="post"> <input type="hidden" name="token" value="secret_elves_token" /> <!-- Elves love secrets --> <button type="submit">Summon The Elves</button> <!-- Launch the elf magic --> </form>

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:

<button type="submit" value="unicorn_magic">Fluffy Tails!</button> <!-- The 'unicorn_magic' will be delivered in the POST request -->

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:

<button type="submit" form="rogueForm">Submit from the Shadows</button> <form id="rogueForm" action="/submit_here_from_the_dark" method="post"></form>

On clicking, the button summons the form with ID rogueForm.