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
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)
it's got a ton of uses: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects
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 ...
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)
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
basically, if you're working with forms in javascript, you should be using formData
yup
i cant stress enough how useful it is
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.
it really is extremely useful to handle form data
yep I see, thanks guys 💯