- Using FormData Objects
- Creating a FormData object from scratch
- Retrieving a FormData object from an HTML form
- Sending files using a FormData object
- Using a formdata event
- Submitting forms and uploading files via AJAX without FormData objects
- Gotchas
- See also
- Found a content problem with this page?
- How to Submit a Form with JavaScript – JS Submit Button Example
- How to Create the HTML Form
- How to Submit a Form with JavaScript
- Conclusion
Using FormData Objects
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest . It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form’s submit() method would use to send the data if the form’s encoding type were set to multipart/form-data .
Creating a FormData object from scratch
You can build a FormData object yourself, instantiating it then appending fields to it by calling its append() method, like this:
const formData = new FormData(); formData.append("username", "Groucho"); formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // HTML file input, chosen by user formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like object const content = 'hey!'; // the body of the new file… const blob = new Blob([content], type: "text/xml" >); formData.append("webmasterfile", blob); const request = new XMLHttpRequest(); request.open("POST", "http://foo.com/submitform.php"); request.send(formData);
Note: The fields «userfile» and «webmasterfile» both contain a file. The number assigned to the field «accountnum» is immediately converted into a string by the FormData.append() method (the field’s value can be a Blob , File , or a string: if the value is neither a Blob nor a File, the value is converted to a string).
This example builds a FormData instance containing values for fields named «username», «accountnum», «userfile» and «webmasterfile», then uses the XMLHttpRequest method send() to send the form’s data. The field «webmasterfile» is a Blob . A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. The File interface is based on Blob , inheriting blob functionality and expanding it to support files on the user’s system. In order to build a Blob you can invoke the Blob() constructor .
Retrieving a FormData object from an HTML form
To construct a FormData object that contains the data from an existing , specify that form element when creating the FormData object:
Note: FormData will only use input fields that use the name attribute.
const formData = new FormData(someFormElement);
const formElement = document.querySelector("form"); const request = new XMLHttpRequest(); request.open("POST", "submitform.php"); request.send(new FormData(formElement));
You can also append additional data to the FormData object between retrieving it from a form and sending it, like this:
const formElement = document.querySelector("form"); const formData = new FormData(formElement); const request = new XMLHttpRequest(); request.open("POST", "submitform.php"); formData.append("serialnumber", serialNumber++); request.send(formData);
This lets you augment the form’s data before sending it along, to include additional information that’s not necessarily user-editable.
Sending files using a FormData object
You can also send files using FormData . Include an element of type file in your :
form enctype="multipart/form-data" method="post" name="fileinfo"> p> label >Your email address: input type="email" autocomplete="on" name="userid" placeholder="email" required size="32" maxlength="64" /> label> p> p> label >Custom file label: input type="text" name="filelabel" size="12" maxlength="32" /> label> p> p> label >File to stash: input type="file" name="file" required /> label> p> p> input type="submit" value="Stash the file!" /> p> form> div id="output">div>
Then you can send it using code like the following:
const form = document.forms.namedItem("fileinfo"); form.addEventListener( "submit", (event) => const output = document.querySelector("#output"); const formData = new FormData(form); formData.append("CustomField", "This is some extra data"); const request = new XMLHttpRequest(); request.open("POST", "stash.php", true); request.onload = (progress) => output.innerHTML = request.status === 200 ? "Uploaded!" : `Error $request.status> occurred when trying to upload your file.
`; >; request.send(formData); event.preventDefault(); >, false, );
Note: If you pass in a reference to the form, the request method specified in the form will be used over the method specified in the open() call.
Warning: When using FormData to submit POST requests using XMLHttpRequest or the Fetch_API with the multipart/form-data Content-Type (e.g. when uploading Files and Blobs to the server), do not explicitly set the Content-Type header on the request. Doing so will prevent the browser from being able to set the Content-Type header with the boundary expression it will use to delimit form fields in the request body.
You can also append a File or Blob directly to the FormData object, like this:
.append("myfile", myBlob, "filename.txt");
When using the append() method it is possible to use the third optional parameter to pass a filename inside the Content-Disposition header that is sent to the server. When no filename is specified (or the parameter isn’t supported), the name «blob» is used.
Using a formdata event
A more recent addition to the platform than the FormData object is the formdata event — this is fired on an HTMLFormElement object after the entry list representing the form’s data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a FormData() constructor.
This allows a FormData object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself.
Typically this is used as shown in our simple formdata event demo — in the JavaScript we reference a form:
const formElem = document.querySelector("form");
In our submit event handler we use preventDefault to stop the default form submission, then invoke a FormData constructor to trigger the formdata event:
.addEventListener("submit", (e) => // on form submission, prevent default e.preventDefault(); // construct a FormData object, which fires the formdata event new FormData(formElem); >);
When the formdata event fires we can access the FormData object using FormDataEvent.formData , then do what we like with it (below we post it to the server using XMLHttpRequest ).
.addEventListener("formdata", (e) => console.log("formdata fired"); // Get the form data from the event object const data = e.formData; for (const value of data.values()) console.log(value); > // submit the data via XHR const request = new XMLHttpRequest(); request.open("POST", "/formHandler"); request.send(data); >);
Note: The formdata event and FormDataEvent object are available in Chrome from version 77 (and other equivalent Chromiums), and Firefox 72 (first available behind the dom.formdata.event.enabled pref in Firefox 71).
Submitting forms and uploading files via AJAX without FormData objects
If you want to know how to serialize and submit a form via AJAX without using FormData objects, please read this paragraph.
Gotchas
The FormData object doesn’t include data from the fields that are disabled or the fieldsets that are disabled.
See also
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.
How to Submit a Form with JavaScript – JS Submit Button Example
Joel Olawanle
When building applications and websites on the internet, you’ll sometimes need your users to supply information by filling out a form.
But then you might wonder – how do you get this data from the form? Well, you can do this with JavaScript.
In this article, you will learn how to create a form and get data from it when the form is submitted with JavaScript.
This article won’t cover how to input data into a database – it will only cover how to submit a form. But you should know that once you have this data, you can send it to the database of your choice, use it to manipulate information, and much more.
To submit a form using JavaScript, you must first create the form and add distinctive, specific attributes to the input fields. You will use these attributes to retrieve the data when the user submits and then calls a function to handle validations (possibly if any data is submitted).
How to Create the HTML Form
To get started, let’s create a basic HTML form with two fields: username and password. We’ll also add a button that will be used to submit the form and trigger a JavaScript action.
To get this form’s data via JavaScript, you’ll need to attach specific attributes to the form input field and the form itself. These attributes can be an id , a class , or even with the name tag. This will help get the data in JavaScript using their document methods.
For example, if you use an id attribute on your input field, you can access the input field data and other values using the document method getElementByID(‘idName’) :
// HTML // JS let myUsername = document.getElementById('username'); console.log(myUsername);
If you use a class attribute, you’ll use getElementsByClassName(className) , which returns an array of all elements with the className . If it is only one element, you can use the index number 0 to access its data:
// HTML // JS let myUsername = document.getElementsByClassName('username'); console.log(myUsername[0]);
If you use the name attribute, you’ll use getElementsByName(name) . This is similar to how the class attribute works since it also returns an array which you can loop through or access with its index number:
// HTML // JS let myUsername = document.getElementsByName('username'); console.log(myUsername[0]);
Note: This will not return the input value but the input element itself.
How to Submit a Form with JavaScript
The first step is to attach your preferred attribute to the form, which you can use to track when the form is submitted. This can be an id , class or name attribute, but for this article, I will use id for the form and input fields:
At this point, you can now handle form submission with JavaScript. You first get the form with your preferred attribute, which can be an id, and store it in a variable:
let loginForm = document.getElementById("loginForm");
Then you can attach the addEventListener to the form variable and listen for a submit event. This event listener allows you to attach a callback function which gets triggered once the form is submitted:
loginForm.addEventListener("submit", (e) => < e.preventDefault(); // handle submit >);
At this point, you can now get the form data and handle any operation you wish. For this article, let’s first validate the data by checking if the input is empty before performing any operation:
loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < // throw error >else < // perform operation with form input >>);
This is the entire JavaScript code:
let loginForm = document.getElementById("loginForm"); loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < alert("Ensure you input a value in both fields!"); >else < // perform operation with form input alert("This form has been successfully submitted!"); console.log( `This form has a username of $and password of $` ); username.value = ""; password.value = ""; > >);
Conclusion
In this article, you have learned how to submit a form with JavaScript and how it works with the various DOM methods.
There are other ways you can do this, but this is a straightforward way to handle submission in JavaScript.
You can access over 150 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.