Submitting Single Form to different Actions in HTML5

Forms in HTML5 will allow you to submit data to different URLs without extra code. We can utilize Browser’s APIs to get more things done with less code.

Submitting Single Form to different Actions in HTML5

For so long, I had believed that one Form could only be submitted to one Action URL without any JS.

I couldn’t be more wrong.

Let's take a look at the way of the Past, i.e. with JavaScript and AJAX/Fetch.


Problem

Consider following HTML Form where we want to add or update addresses to the User Profiles.

<form id='addressForm'>
  ...
  <!-- Form Fields -->
  ...
  <button id='addAddress' class="btn btn-primary">Add Address</button>
  <button id='updateAddress' class="btn btn-success">Update Address</button>
</form>

In the above form, there are submit buttons to Add Address or Update Address Though they will only send POST request to /addAddress .

This means the Update Address will still lead to adding a new address rather than updating the current one.

To make this work, we will need to use JavaScript.

Now with JavaScript, there are multiple ways to do so. A straightforward way is to submit the form via AJAX request.

Let’s see how to submit the above Form to different Action endpoints with AJAX:

document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('#addressForm')
  const addButton = document.querySelector('#addAddress')
  const updateButton = document.querySelector('#updateAddress')

  addButton && addButton.addEventListener('click', (e) => {
    e.preventDefault()

    if (!form.checkValidity()) {
      return
    }

    fetch('/addAddress', { method: 'POST', body: new FormData(form) })
      .then((r => r.json()))
      .then(console.log)
  })
  
  updateButton && updateButton.addEventListener('click', (e) => {
    e.preventDefault()

    if (!form.checkValidity()) {
      return
    }

    fetch('/updateAddress', { method: 'POST', body: new FormData(form) })
      .then((r => r.json()))
      .then(console.log)
  })
})

As we can see with JavaScript, the HTML and deform submitting are very tightly coupled.

This old way of sending Forms to multiple endpoints can be checked at https://multi-action-forms.netlify.app/with-ajax.html.

Here were using Browser's FormData API and Fetch API; you can read more about them here:

FormData API: Handle Forms like Boss ? - Time to Hack
Handling Forms has always been confusing as there are many ways to do so. Let’s take a look at the cool features of FormData API to handle Forms.
GoodBye XMLHttpRequest; AJAX with fetch API (with Demo) - Time to Hack
AJAX is a crucial part of any Web App. The primary way to do AJAX is through XMLHttpRequest. JavaScript has new fetch API which will remove the need to use the weird XMLHttpRequest

Now what is the solution?

Solution

I came across these attributes for the submit buttons, where you can specifically make the form to be submitted on different URLs with different HTTP methods and encoding types.

Those attributes are fromaction, formmethod and formenctype.

With these attributes, we can go back to adding a standard submit button and default attribute to the form.

We will also add another submit button with the attributes mentioned in the previous line.

Here’s what the new HTML Form will look like:

<form action="/addAddress" method="POST">
  ...
  <!-- Form Fields -->
  ...
  <button type="submit" class="btn btn-primary">Add</button>
  <button type="submit" class="btn btn-success" formaction="/updateAddress" formmethod="POST">Update</button>
</form>

Not just on Buttons, but on the input of type button also accepts these attributes to allow sending Form Submissions to different endpoints.


Benefits

  • No need to attach JS for basic functionalities
  • HTML5 Validation API can be leveraged with its normal flow
  • The form can work in Pages with JS disabled (with exceptions)

Concerns

  • Browser Support, the old browsers might not work with this, and hence you might need Polyfills/Shims
  • Modern Front End apps like Single Page Applications, MicroFrontends etc., might need extra tuning to work with this.

Github Repo Demo

Conclusion

We saw how we could utilize the Browser’s inbuilt APIs to get more things done with less code.

Would you use in you application? Why or Why not?

Let me know through comments ? or on Twitter at @heypankaj_ and @time2hack

If you find this article helpful, please share it with others ?

Subscribe to the blog to receive new posts right in your inbox.


Credits


This post is sponsored by PluralSight

PluralSight