Building a form is easy to do as long as you don’t have an edge case. Then the bacon fat goes down the drain and your pipes are ruined. So you sometimes need some extra tools in your toolbelt to deal with it. The FormData API
can be one of your tools.
FormData has a lot of features but the only method that works across all browsers is append
. Let’s say we want to create a social application for people to share their bacon pictures. Here we’ll create a form that allows users to send a picture with a title and the author’s name. Our HTML markup will look like this:
To handle our data we can create the following code:
If this is our input:
Then we press the submit button we’ll roughly get the following request headers:
And the following body:
Please note that FormData
constructor can take form data as an argument. So you could do:
Another important gotcha, is that append
does not overwrite a key if it already exists.
If you want to overwrite a key value you will have to use other functions.
The FormData
constructor and the append
method are available in all browsers. Most of the other methods are pretty self-descriptive:
FormData.has(key)
: Checks if the key exists in the form.FormData.set(key, value)
: Changes the value associated to the key.FormData.delete(key)
: Deletes the entry associated with the key.FormData.get(key)
: Accesses the first value associated with the key.FormData.getAll(key)
: Creates an array of all the values associated with a key.FormData.keys()
, FormData.values()
, FormData.entries()
: Iterators used to get all the keys, associated values or just entries of the FormData.🥓 That’s it if you have any questions you can fire them up on Twitter with a link to the article and I’ll do my best to answer them!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!