FormData() in Javascript

FormData() in Javascript

Basically we use the formData() method to push data onto an object that will then send to a server using the XMLHttpRequest.send(). FormData objects are used to capture HTML form and submit it using fetch or another network method. They are commonly used to send form results (input name alongside with its values) to a server without navigating.

We can either create new FormData(form) from an HTML form, or create an object without a form at all, and then append fields with methods:

  • formData.append(name, value)
  • formData.append(name, blob, fileName)
  • formData.set(name, value)
  • formData.set(name, blob, fileName)

A basic example is:

var send = function() {
    var request = new XMLHttpRequest();
    // POST to httpbin which returns the POST data as JSON
    request.open('POST', 'https://httpbin.org/post', /* async = */ false);

    var formData = new FormData(document.getElementById('test-form')); // create the formData object from the form inputs field names and values

    formData.append('key1', 'value1'); // append new values to the object
    formData.append('key2', 'value2');

    request.send(formData);
  };

When using FormData method, the name for form input is mandatory to construct the object to send to the server. In case you miss the name, below is a sample that will add the country entity onto the formData object as the country field does not have the name attribute. The form.set method is used to push a new entity onto the formData.

Example available on Codepen

###Basic HTML###

<link rel="stylesheet" text="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" />
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8">
      <div id="playground" class="border rounded my-3 p-3">
<form id="profileForm" name="profileForm">
<div class="row mb-1">
  <div class="col-md-3">Name</div>
  <div class="col"><input type="text" class="form-control" name="name" placeholder="Name" /></div>
  </div>
  <div class="row mb-1">
  <div class="col-md-3">Name</div>
  <div class="col"><input type="text" class="form-control" name="name" placeholder="Name" /></div>
  </div>
    <div class="row mb-1">
  <div class="col-md-3">Name</div>
  <div class="col"><input type="text" class="form-control" name="name" placeholder="Name" /></div>
  </div>
      <div class="row mb-1">
  <div class="col-md-3">Name</div>
  <div class="col"><input type="text" class="form-control" name="name" placeholder="Name" /></div>
</div>
<div class="row mb-1">
  <div class="col-md-3">URL</div>
  <div class="col"><input type="text" class="form-control" name="url" placeholder="URL" /></div>
</div>
<div class="row mb-1">
  <div class="col-md-3">Country</div>
  <div class="col"><input type="text" class="form-control" id="country" placeholder="Country" /></div>
</div>
<div class="row mb-1">
  <div class="col-md-3">Photo</div>
  <div class="col"><input type="file" class="form-control" name="photo" /></div>
</div>
<div class="row mb-1">
  <div class="col-md-3">Hobbies</div>
  <div class="col">

    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="Sports" name="hobbies" id="hobbies-Sports">
      <label class="form-check-label" for="hobbies-Sports">Sports</label>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="Music" name="hobbies" id="hobbies-Music">
      <label class="form-check-label" for="hobbies-Music">Music</label>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="Reading" name="hobbies" id="hobbies-Reading">
      <label class="form-check-label" for="hobbies-Reading">Reading</label>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="Painting" name="hobbies" id="hobbies-Painting">
      <label class="form-check-label" for="hobbies-Painting">Painting</label>
    </div>
  </div>
</div>
</form>

<button class="btn btn-outline-primary" id="showData">Show Data</button>
<button class="btn btn-outline-dark" id="showAllData">Show All Data</button>
</div>
    </div>
    <div class="col-md-4">
      <pre id="data" class="hidden border rounded my-3 p-3">
</pre>
    </div>
  </div>
</div>

###JS###

const objectFromFormData = function(formData) { var values = {}; for (var pair of formData.entries()) { var key = pair[0]; var value = pair[1]; if (values[key]) { if ( ! (values[key] instanceof Array) ) { values[key] = new Array(values[key]); } values[key].push(value); } else { values[key] = value; } } return values; }

document.querySelector('#showData') .addEventListener('click', function(e) { e.preventDefault(); const form = new FormData(document.forms['profileForm']); preview(form); });

document.querySelector('#showAllData') .addEventListener('click', function(e) { e.preventDefault(); const form = new FormData(document.forms['profileForm']); form.set('country', document.querySelector('#country').value); preview(form); });

function replacer(key, value) { if (value instanceof File) { return ['name', 'size', 'type'].reduce(function(acc, key) { acc[key] = replacer(key, value[key]); return acc; }, {}); } return value; }

function preview(form) { var data = document.querySelector('#data') var txt = JSON.stringify( objectFromFormData(form), replacer, 2); data.innerHTML = txt; data.classList.remove('hidden'); data.scrollIntoView(); } ```