DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

How to use formData Web API to collect form data

You are given the following form and asked to complete a simple task to gather data from the form fields

index.html

<div class="container">
  <div class="header"> <h4> Register </h4>
    </div>
<form class="myForm">

  <div class="message">
    <label for="msg">Message</label>
    <textarea id="msg"></textarea>
  </div>
  <div class="contact">
    <label for="name">Name</label>
    <input type="text" id="name">

    <label for="favSong">Your favourite song</label>
    <input type="text" id="favSong">

    <label for="email">Email Address</label>
        <input type="email" id="email"> 
        <label>Choose Image for your profile</label>
        <input type="file" name="profile-image" id="form-profile-image" accept="image/*">
    <button onclick="submitProfile()" >Submit</button>
  </div>
</form>
</div>
<script src="src/index.js"></script>
Enter fullscreen mode Exit fullscreen mode

Task

Using the FormData web API complete the submitProfile() function which will let us send post data of the field values to API URL given below

//index.js

const API_URL = "http://localhost:3000/api/user";

const submitProfile = ()=>{
   //complete the code
}
Enter fullscreen mode Exit fullscreen mode

The example post object should look like this

{
name:"",
msg:"",
email:"",
imageFile:"",
favSong:""
}
Enter fullscreen mode Exit fullscreen mode

Steps to solving this

  1. Assign a variable to the value of the field using getElementByID, for example for name we can something like const name=document.getElementById('name')

  2. Initialize formData() and assign it to a variable 'data'

  3. Append all the values to data variable using .append()

  4. Then use fetch() to post the data object to the API url given.

These steps can be implemented as follows

Complete code for this can be found here https://codesandbox.io/s/shy-moon-n0jdtx?file=/index.js

Top comments (4)

Collapse
 
v3nci profile image
v3nci

The code you wrote, can be refactored and improved, so here are some tips:

  1. Use <button type="submit">, clicking it will submit the form. It's better to watch for form submitting event than the button click.
  2. When using new FormData, you can pass the form object itself. So your entire submitProfile function can become so much shorter, something like:
// HTML
<form id="myForm>form fields here</form>

// JS
const myForm = document.getElementById('myForm');

myForm.addEventListener('submit', (event) => {
    event.preventDefault();

    const form = event.target;
    const formData = new FormData(form);
    const formProps = Object.fromEntries(formData);

    // do the request afterwards
});
Enter fullscreen mode Exit fullscreen mode

formProps will be an object, having your form data. Also, this way you won't have to specify and find each form input field.

Collapse
 
brense profile image
Rense Bakker

Even cleaner would be to use the onsubmit property of the HTML form:

function handleSubmit(event){
  event.preventDefault();

  const form = event.target;
  const formData = new FormData(form);
  const formProps = Object.fromEntries(formData);

  // do the request afterwards
}

<form onsubmit="handleSubmit">
  // your form fields...
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
azzarox profile image
Azzarox

As long as a button is inside form tag it will submit by default so no need for the type unless you want to be explicit

Collapse
 
naveenkolambage profile image
Naveen Dinushka

Thanks!!