Collecting data from a form with the FormData interface

Collecting data from a form with the FormData interface

Introduction

js this

Using the FormData interface makes working with forms quite easy, because it is able to simply pick up all the input values in the form and store them in an object as key/value pairs.
An additional advantage over the standard method is related to easier writing of server code. With the standard method we have to add a certain code on the server side that would process the 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 the form all HTML input tags must have the ‘name’ attribute, because FormData has access to the input values through it.

Syntax

a) Data collection from the whole form

When we want to collect all form input values then we use:

The

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

Example:

JavaScript

PHP (submit.php)

formData example

b) Collection of specific data from the form

If we want to attach only one piece of data to the FormData object (i.e. one pair of key/value), we need to create an empty formData object to which we subsequently add the desired key/value

then we can use the following syntax:

Arrive on the server:

MDN snippet

EventHandler snippet

If you have several forms, in order not to repeat the code, we can use a snippet recommended by the MDN community that covers all possible ways of sending data. A function AJAXSubmit is defined in the code, which accepts a form object as an argument. After that, it is enough in each of our forms to just define a callback after form submission onsubmit="AJAXSubmit(this);.

Application of MDN snippet

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

If different types of data are collected from the form (if files are also sent in addition to text), then the body of the request must consist of parts that are separated by boundaries “boundary”. Therefore, it is necessary that there is a “Content-Type” field in the header that defines the “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