Sometimes, you have an old school HTML form, but your front end interacts with an API. Submitting the form this way can be tricky. In this blog post, we will explore a clean way to do so.
The source code can be found here.
The following approach will enable the developer to submit any HTML form to a "POST" API endpoint. Following are the steps:
- Create the form with its inputs and submit input/button as you would normally do.
- Give the form a unique Id.
- Add a submit event listener to the form and pass the event object with it.
- Build the request body in JSON format using the FormData class.
- Add any headers, if needed.
- Call the API using fetch or Axios (or any tool of your preference).
- Change the window's location upon a successful response or show a notification if there are any errors.
We will create a simple form that will be submitted to JSON PlaceHolder as an example.
As you might have noticed, we called the function buildJsonFormData. It simply uses the object FormData to construct a set of key-value pairs in JSON format. It does that by looping over all inputs in the form and appending each key value pair to the JSON object, like so:
Typically, you'd add headers to your request. You can checkout the sample function in app.js in the source to see one way to do it.
In this blog post, we explored an effective and reusable way of submitting HTML forms to JSON APIs.
Cover Image credit.