Can a HTML button perform a POST request?

Solution 1:

You need to give the button a name and a value.

No control can be submitted without a name, and the content of a button element is the label, not the value.

<form action="" method="post">
    <button name="foo" value="upvote">Upvote</button>
</form>

Solution 2:

This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.

<form action="" method="post">
    <input type="submit" name="upvote" value="Upvote" />
</form>

Solution 3:

You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:

const button = document.getElementById('post-btn');

button.addEventListener('click', async _ => {
  try {     
    const response = await fetch('yourUrl', {
      method: 'post',
      body: {
        // Your body
      }
    });
    console.log('Completed!', response);
  } catch(err) {
    console.error(`Error: ${err}`);
  }
});
<button id="post-btn">I'm a button</button>

Solution 4:

You can:

  • Either, use an <input type="submit" ..>, instead of that button.
  • or, Use a bit of javascript, to get a hold of form object (using name or id), and call submit(..) on it. Eg: form.submit(). Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.