loading...
Cover image for Submit HTML Forms to JSON APIs easily

Submit HTML Forms to JSON APIs easily

amjadmh73 profile image Amjad Abujamous ・2 min read

Motivation

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.

Code

The source code can be found here.

Approach

The following approach will enable the developer to submit any HTML form to a "POST" API endpoint. Following are the steps:

  1. Create the form with its inputs and submit input/button as you would normally do.
  2. Give the form a unique Id.
  3. Add a submit event listener to the form and pass the event object with it.
  4. Build the request body in JSON format using the FormData class.
  5. Add any headers, if needed.
  6. Call the API using fetch or Axios (or any tool of your preference).
  7. Change the window's location upon a successful response or show a notification if there are any errors.

Step 1: The form

We will create a simple form that will be submitted to JSON PlaceHolder as an example.
Simple Form

Step 2: The form Id and the event listener

We will add an Id to the form and we will register an event listener to it, like so:
Form Id
Event Listener

Step 3: The function

The function will build the JSON body, build the request headers, and use the fetch service to POST the request by the submitted the form. This is how it looks like:
Function

Step 4: Building the body

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:
Json Form Function

Step 5: Adding Headers

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.

Step 6: Submitting a request using Fetch

Now, the Fetch Service is what we built to submit any request and get the response so that we don't have to keep rewriting its logic. Since the code is self-explanatory, take a look:
POST Request Function

Step 7: Done. Informing the user or changing the page

Finally, we will navigate to the page that says "Success" and, for simplicity, show response data in the URL.
Success

Conclusion

In this blog post, we explored an effective and reusable way of submitting HTML forms to JSON APIs.
Cover Image credit.

Posted on by:

amjadmh73 profile

Amjad Abujamous

@amjadmh73

Junior Developer who enjoys coding and building stuff.

Discussion

pic
Editor guide