How to Use the FormData Object

02/03/2022

Contents

In this article, you will learn how to use the FormData Object.

What is the FormData object?

The FormData object is an object used to send data to the server.
You can send the form data entered by the user or any data to the server.

The syntax is below.

let formData = new FormData();
formData.append("key", "value");

You can also create a FormData object from the HTML form element as shown below.

let formData = new FormData(document.forms.form1);

Sample Code

Below is sample code that creates a FormData object from an HTML form element and then adds a value to the FormData instance on JavaScript.
If you display the contents of the FormData instance on the console, you can see that the value in the HTML form element and the key and value added by append are output.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>How to Use the FormData Object</title>
</head>
<body>
  <form id="form1" action="#" onsubmit="return myFunc()">
    <input type="text" id="input_message" name="input_message" value="">
    <input type="checkbox" id="input_check" name="input_check" value="oncheck" checked>
    <input type="submit" value="Send">
  </form>
  <div id="output_message"></div>
  <script language="javascript" type="text/javascript">
    function myFunc() {
      let formData = new FormData(document.forms.form1);
      formData.append("key1", "value1");
      for (item of formData) {
        console.log(item);
      }
      return false;
    }
  </script>
</body>
</html>