What is the purpose of the instance of FormData?

Hello guys, sorry to disturb you all; I have just learnt about FormData. I know it is mostly used for file uploads. But I don't understand how does it work, like sometimes peiple use an instance of FormData like formData to append something. For e.g: formData.append('name', value) I don't understand when do we use this formData.append ? Sometimes the form element reference is passed directly into the FormData constructor and we no longer need it... I'm a bit confuse of how it work, what if we need to upload multiple files for e.g.
9 Replies
snxxwyy
snxxwyy2w ago
i'm not actually too familiar myself but it creates a form object that you can manipulate i believe. The input tag's name attribute is equal to formData.append('name', value) e.g. <input name="phoneNumber">. You'd say formData.append('name', phoneNumber)
Jochem
Jochem2w ago
MDN Web Docs
Using FormData Objects - Web APIs | MDN
The FormData object lets you compile a set of key/value pairs to send using the Fetch or XMLHttpRequest API. 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 ...
Jochem
Jochem2w ago
it's a really convenient way to access all the data on a form, you can cram it straight into the body property on a fetch POST request, and you can manipulate it before sending it it's also just a really simple way to get data from a form that you don't intend to submit, so you don't have to have twenty const name = document.querySelector('#name'); lines, but you can just do const data = new FormData(event.target)
ἔρως
ἔρως2w ago
it's also very convenient to change the form data before submitting, including adding files to it and it's also incredibly convenient to send it over xhr/fetch
Jochem
Jochem2w ago
basically, if you're working with forms in javascript, you should be using formData
ἔρως
ἔρως2w ago
yup i cant stress enough how useful it is
Chris Bolson
Chris Bolson2w ago
100% agree with Epic and Jochem. I use FormData a lot, especially when sending via fetch, something I am doing continually in my current project.
ἔρως
ἔρως2w ago
it really is extremely useful to handle form data
Faker
FakerOP2w ago
yep I see, thanks guys 💯
Want results from more Discord servers?
Add your server