Introduction

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:
|
1 2 |
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 associates the encoded input value with it.
Example:
|
1 2 3 4 5 6 7 8 9 10 11 |
<form id="myform" name="myform"> <div> <label for="username">Unesi ime:</label> <input type="text" id="username" name="username"> </div> <div> <label for="userTel">Unesi telefonski broj:</label> <input type="text" id="userTel" name="userTel"> </div> <input type="submit" value="Send!"> </form> |
JavaScript
|
1 2 3 4 5 6 7 8 |
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)
|
1 2 3 4 5 |
<?php echo "<pre>"; print_r( $_POST); echo"</pre>"; ?> |

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
|
1 |
formData.append('nameImputa', unetaVrdnost); |
then we can use the following syntax:
|
1 2 3 4 5 6 7 8 9 10 |
document.getElementById("myform").onsubmit = function(event) { event.preventDefault(); var eForma = event.target; var formData = new FormData(); // New empty object var vrednostInputa = document.getElementById("username").value; formData.append('backendKljucIme', vrednostInputa); var xhr = new XMLHttpRequest(); xhr.open("POST", "submit.php"); xhr.send(formData); } |
Arrive on the server:
|
1 2 3 4 |
Array ( [backendKljucIme] => Dragoljub ) |
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);.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// 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 part related to the success of AJAX requests: function ajaxSuccess () { console.log(this.responseText); } |
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
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<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 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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<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> |

