Collecting Form Data with FormData Interface

FormData

Using the FormData interface makes it much easier to handle forms, as it is able to simply pick up all the input values in a form and store them in the object in the form of key/value pairs.
An additional advantage over the standard method is the ease of writing server code. With the standard method, we need to add some server-side code that would process incoming data in a specialized way, while with FormData it is not necessary, because the code sent is standardized and debugged! It should be emphasized that in form all HTML input tags must have the attribute ‘name‘ because FormData has access to the input values through it.

Collecting data from the entire form

When we want to pick up all values of form input then we use:

var myForm = document.getElementById('form-id');
formData = new FormData(myForm);

The FormData object is populated with keys/values pairs. JavaScript uses the name property for each form element as keys and assigns it an encoded input value.

Example

<form id="myform" name="myform">
      <div>
        <label for="username">Name:</label>
        <input type="text" id="username" name="username">
      </div>
      <div>
        <label for="userTel">Phone Number:</label>
        <input type="text" id="userTel" name="userTel">
      </div>
    <input type="submit" value="Send!">
</form>

JavaScript

document.getElementById("myform").onsubmit = function(event) {
    event.preventDefault();
    var eForma = event.target;
    var formData = new FormData(eForma);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "submit.php");
    xhr.send(formData);
}

PHP (submit.php)

<?php
    echo "<pre>";
    print_r( $_POST);
    echo"</pre>";
?>

Collecting specific form data

If we want to associate a FormData object with only one data (for example, one key/value pair), we need to create a blank formData object to which we subsequently add the desired key/value

formData.append('Inputname', EnterValue);

then we can also use the following syntax:

document.getElementById("myform").onsubmit = function(event) {
    event.preventDefault();
    var eForma = event.target;
    var formData = new FormData();   // New empty object
    var valueInput= document.getElementById("username").value;
    formData.append('backendKeyName', valueInput);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "submit.php");
    xhr.send(formData);
}

The server arrives at:

Array
(
    [backendKeyName] => Alen
)

MDN snippet

EventHandler snippet

If you have more than one form to avoid repeating the code, we can use a snippet recommended by the MDN community that covers all possible ways of sending data. The code defines an AJAXSubmit function that accepts a form object as an argument. After that it is enough in each of our forms to just define a callback after submit the form onsubmit = “AJAXSubmit (this) ;.

// EventHandler function
function AJAXSubmit (oFormElement) {
  if (!oFormElement.action) { return; }d
  var oReq = new XMLHttpRequest();
  oReq.onload = ajaxSuccess;
  if (oFormElement.method.toLowerCase() === "post") {
    oReq.open("post", oFormElement.action);
    oReq.send(new FormData(oFormElement));
  } else {
    var oField, sFieldType, nFile, sSearch = "";
    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
      oField = oFormElement.elements[nItem];
      if (!oField.hasAttribute("name")) { continue; }
      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ?
          oField.getAttribute("type").toUpperCase() : "TEXT";
      if (sFieldType === "FILE") {
        for (nFile = 0; nFile < oField.files.length;
            sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
      }
    }
    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
    oReq.send(null);
  }
}
 
// The AJAX performance part requires:
function ajaxSuccess () {
  console.log(this.responseText);
}

Application of MDN snippets

n order for the previous snippet to have a purpose, it is necessary to define through the form attribute which EventHandler function is onsubmit = “AJAXSubmit (this)

<form action="submit.php" method="post" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Registration example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" />
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

If data from different types are collected from the form (if files are to be sent in addition to the text), then the request body must consist of parts separated by boundaries. Therefore, it is necessary that the header contains a “Content-Type” field that defines a “multipart” body enctype = “multipart / form-data”

The content type “application/x-www-form-urlencoded” is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type “multipart/form-data” should be used for submitting forms that contain files, non-ASCII data, and binary data.
https://www.w3.org

Example

<form action="submit.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
  <fieldset>
    <legend>Upload example</legend>
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" /><br />
      Sex:
      <input id="sex_male" type="radio" name="sex" value="male" />
      <label for="sex_male">Male</label>
      <input id="sex_female" type="radio" name="sex" value="female" />
      <label for="sex_female">Female</label><br />
      Password: <input type="password" name="secret" /><br />
      What do you prefer:
      <select name="image_type">
        <option>Books</option>
        <option>Cinema</option>
        <option>TV</option>
      </select>
    </p>
    <p>
      Post your photos:
      <input type="file" multiple name="photos[]">
    </p>
    <p>
      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
      <label for="vehicle_bike">I have a bike</label><br />
      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
      <label for="vehicle_car">I have a car</label>
    </p>
    <p>
      Describe yourself:<br />
      <textarea name="description" cols="50" rows="8"></textarea>
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </fieldset>
</form>

Likes:
15 0
Views:
1479
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *