Using FormData Objects Effectively

  Рет қаралды 36,718

Steve Griffith - Prof3ssorSt3v3

Steve Griffith - Prof3ssorSt3v3

4 жыл бұрын

This video explains how you can use a FormData object to quickly and easily grab all the data from any form and send that to a web server.
You can even convert that data into JSON data and send that to the server.
Code from the video: gist.github.com/prof3ssorSt3v...

Пікірлер: 101
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Clarification: The convertFD2JSON function does NOT need to be an async function. In my head I was thinking about making a fetch call and that would have needed to be async. You can remove the `async` and `await` key words from this code. I have made this change in the code sample linked in the description. - gist.github.com/prof3ssorSt3v3/7be8dd12f4d022932a3f700e0cef1841
@allanregista4422
@allanregista4422 4 жыл бұрын
Hey, thank you for the clarification there, my confusion has been vanished 👍👍👍. Im a bit confused earlier..
@sacrajah
@sacrajah 3 жыл бұрын
Thank you
@viniciusmelo1930
@viniciusmelo1930 2 жыл бұрын
thanks for the clarification, Steve, was stuck at this point... great channel, btw!
@trophieboi1820
@trophieboi1820 4 жыл бұрын
I watched your Cordova tutorials two years ago. helped me a lot. can't believe u are still uploading. u helped me code when I was jus starting with js. a big thank u.
@allanregista4422
@allanregista4422 4 жыл бұрын
This is the tutorial I've been searching for... That preventDefault explanation helps my flashing php response. Thank you for making this and for your efforts sifu. May God always be with you 🙏. U just earned a new sub. Would u kindly please make more of web programming tutorials.
@kikish_sabina
@kikish_sabina Жыл бұрын
Steve Griffith, thank you so much! I was trying to fix the bug whole day, after watching this video, I have fixed it, thank you so much! I addressed many qualified developers about this bug, but they couldn't deal with that😢 ❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤ I regret to not to find you earlier! Thank you!
@Gollumfili
@Gollumfili 2 жыл бұрын
I wish I would have arrived at this video first. It would have saved me loads of time and wasted effort, so methodically and well explained. Thank you.
@dimplechhapolia1247
@dimplechhapolia1247 3 жыл бұрын
i have learnt a lot from your videos, i have been struggling to post FormData to rest api, at api end my data was not being read. after watching your video i got to know i need to convert formData to json and it worked.Thanks a ton!!
@ms365developer3
@ms365developer3 4 жыл бұрын
Excellent tutorial. Your voice is so soothing.
@kevinrayparas3094
@kevinrayparas3094 4 жыл бұрын
my best professor all time i watched your all javascript tutorial
@Colstonewall
@Colstonewall 4 жыл бұрын
Awesome, Steve! Thanks my friend.
@saifhamdare72
@saifhamdare72 Жыл бұрын
Video we don't deserve but the video we need 🙌🏻. Really helpful was searching for such a beautifully explained video about form data and forms over all. And youtube suggested me this awsm video🚀. Got a new subscriber man
@pauloramos7032
@pauloramos7032 2 жыл бұрын
Stumbled onto your channel via this video Just really wanted to say thank you for your tutorials. I'm a web developer with a couple of decades under my belt, weaning myself off jQuery Been slowly going through your other JavaScript videos and they have been really helpful. Mostly suck eggs, but a lot of reinforcement and picking up bits and pieces that are rounding out my knowledge with some Aha! moments thrown in. Like scratching an annoying itch when you fill gaps in understanding that have been bothering you for years So thank you Sir ;)
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
Make sure you have a look at the jQuery rehab playlist.
@pauloramos7032
@pauloramos7032 2 жыл бұрын
Yes, saw that and have watched a couple already.
@iwswordpress
@iwswordpress 4 жыл бұрын
Very useful...good to see you back :)
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Glad to be back.
@rubenvandevelde555
@rubenvandevelde555 3 жыл бұрын
me: Fetch formData: empty me: fetch again formData: empty me: :( Steve: add a name attribute me: :)
@mackynikat8833
@mackynikat8833 2 жыл бұрын
. i was foguring this out starting yesterday and after almost already having can hang on this i remember this vid that i've watched b4 . haha , very neat explanation prof . on my way on the next vid still bwt this
@yannicknana
@yannicknana 4 жыл бұрын
Very interesting ! I didn't know handling forms could be less exhaustive
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Almost makes them fun, right?
@Pareshbpatel
@Pareshbpatel 2 жыл бұрын
Excellent demonstration of extraction, and use of Form data. Thanks. {2022-07-12}}
@mohamedatef97
@mohamedatef97 2 жыл бұрын
Great video 👍👌🤞🙏❤️
@jangidpulkit9763
@jangidpulkit9763 2 жыл бұрын
Thank you sir!
@RedEyedJedi
@RedEyedJedi 3 жыл бұрын
Amazing, informative and detailed video as always Steve, thank you for making it. lol @ your I love spam, checkbox joke.
@ContraHacker1337
@ContraHacker1337 2 жыл бұрын
Thank you.
@nextleveltech267
@nextleveltech267 23 күн бұрын
Thank you
@hernangarcia77
@hernangarcia77 3 жыл бұрын
great, you save my wasted time!! Thanks!!
@mackynikat8833
@mackynikat8833 2 жыл бұрын
. finally did it prof after almost 16 hours of straight work . thanks to ur neatness my empty pauses dream finally got a final soluttion . i can now use axios with the loops you indicated here to use fd in axios to prevent myself not to reload the page on submit on my srr website which also means i can already execute jargons pre/post submit while having proper headers and sending it neat on server . haha , going to sell this for $41k to $53k ^^_
@nChauhan91
@nChauhan91 Жыл бұрын
Quick tip: For converting formdata to an Object use Object.fromEntries(formDataObject)
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
Thanks for mentioning that.
@42HUE
@42HUE 3 жыл бұрын
Great video! If I wanted to group my json file with sub groups, say, city, state, and street under address, how could I do that?
@zimani7g473
@zimani7g473 4 жыл бұрын
prof3ssorSt3v3 ♥
@rickyu1978
@rickyu1978 4 жыл бұрын
great video. FD can also attach files from the File Object Api ? Also i noticed yo used new Request, what is the difference between fetch(url) and request? ive actually never seen request like that before, just found out it is part of the fetch api.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Yes. The FormData object is how I attach files to the Request object to upload them. - kzbin.info/www/bejne/gKWuepanj8l_gq8
@ade-ajayiabolaji4005
@ade-ajayiabolaji4005 2 жыл бұрын
I so much much your videos thanks alot, i kept on getting an empty object when sending to a node backend
@tubeviewerification
@tubeviewerification 4 жыл бұрын
You should use a mascot, or even better, a puppet for entertainment value.
@Coretalless
@Coretalless 2 жыл бұрын
I have 3 Excel spread sheets I'm trying to a page to reference. When a user enters a zip code it will, depending on zipcode, lookup data from one of 2 spreadsheets and when someone enters a number in the number of people field it will select a column in the associated spreadsheet. I'm also struggling to get my page to give a grand total of the 5 forms I have added the page.
@4541047
@4541047 4 жыл бұрын
Nice tutorial. But I have a question, Why you added an await to call non-promised function?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Brain fart. Was thinking about fetch... promises... for await of when doing the conversion.
@lars-dimdiy-howtos464
@lars-dimdiy-howtos464 Жыл бұрын
Thank you for your numerous helpful videos. Sorry to bother you however I have spend days trying to figure out how to do what believe should be simple task. I'd rather ask to make sure it is doable and not just my lack of not using/getting the right syntax/typing/etc. I'm trying to eliminate (filter out) any fields that formData has captured with empty " " values. I can't get filter method to work and trying to do an "if" on 'value' to then use a formdata.delete has been futile as well.. Is there a simple way to do this and I've just not hit the correct JS coding for it.. I need to then map the fields but want to get rid of unnecessary first.
@lars-dimdiy-howtos464
@lars-dimdiy-howtos464 Жыл бұрын
Closer if I use this: donated.forEach(function(fname) {if(fname === null || fname.trim() === "") { console.log(fname);}} ); Will return only the 5 fields in the form that have empty strings but donated.forEach(function(fname) {if(fname === null || fname.trim() === "") { donated.delete(fname);}} ); doesn't delete them from the formData array .. so close I think.. will try with filter too
@lars-dimdiy-howtos464
@lars-dimdiy-howtos464 Жыл бұрын
Yeah - Finally - I just wasn't getting the dif between an Object/FormData and Array. Since FormData is (correct me as needed) an 'object' type the filter doesn't work on it. Also if I just convert it to a straight array using a 'for' with 'push' my filter on that also did not work as I was looking for. What was needed was to get an array 'from' my FormData object. Then I had an array of array pairs that let me filter out selectively by the 'value' of the key/value pairs. Yeah! That then allowed sending it back to original object/string pairs format(if needed). const gForm = new FormData(document.forms[1]) var gArray = []; for (const gField of gForm.entries()) {gArray.push (`${gField[0]}, ${gField[1]}`)}; yields a straight array ie ["key","value", "key", "value", ..] const aa2array = Array.from(gForm) yields an array of arrays ie [ ["key","value"] ["key","value"] ["key", "value"]...] const aa2filtered = aa2array.filter(([key, value]) => value === '3803'); filters out all but "3803" ie [["post_id","3803"]] const aa5filtered = aa2array.filter(([key, value]) => value !== ""); filtered out "" / empty string values ie only non empty string values [["key","value"]..] const backobject2 = Object.fromEntries(aa5filtered); turned back into object(strings) ie { key:"value", key:"value", key:"value" ..}
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
You got it. FormData, Object, and Array are different types of Objects and therefore have different properties and methods that are available. The FormData object also has three methods that you could use to get an array. keys( ) - an array of the names values( ) - an array of the values entries( ) - an array of arrays that each holds one name and one value.
@viniciusmelo1930
@viniciusmelo1930 2 жыл бұрын
the CORS error has to do with sending JSON to the server... that's why the browser didn't catch the form-data POST request: "The only values for the Content-Type header in a simple request are the following: application/x-www-form-urlencoded multipart/form-data text/plain"
@mykalimba
@mykalimba 4 жыл бұрын
I don't see the need to add async/await to the convertFD2JSON() function call. It doesn't look like it does anything asynchronously. What am I missing?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
It's not needed. Brain fart. Was thinking about fetch... promises... for await of when doing the conversion.
@mackynikat8833
@mackynikat8833 2 жыл бұрын
. wow . this one was really neat it's only that it uses document which i dont have , hehe. still need to screw it up regarding on ssr but its going to be ok , i got already a hunches on to sort fd's . hehehe , i was trying to use axios on UI prof forms not going to work for what i wanted i was aiming for loading indicators for an admin for crud operations
@mackynikat8833
@mackynikat8833 2 жыл бұрын
. this was suppose to be on the next tuts , hahaha
@sapnadorbi9142
@sapnadorbi9142 3 жыл бұрын
Hello Sir, Please explain, how fd.keys() has iterable data because I had have done console.log(fd) then got prototype, checked the "keys" in prototype but didn't found any values.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
You can't look through the values inside prototype in the console. You need to loop through the collection returned by the fd.keys method to console.log them.
@dangerass1982
@dangerass1982 3 жыл бұрын
Hi Steve, I am working on a form and want to use one button - add - to append key/value pairs to a JS array, so it'll look like [{}, {}, ...]. I've gotten this far. Now, I want to take that array and send a POST request when the user clicks a second button - submit. I think the solution is here, but I'm not quite sure. Do you have any recommended tutorials or videos. I'm kinda lost in the sea of information.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
Convert your array of objects into a single string using the JSON.stringify( ) method. Then you can pass it to the server as a single formdata field. I have a whole playlist of videos about AJAX/fetch that talk about uploading data and everything you need to know to do this. kzbin.info/www/bejne/bXaulpWYabuIj7M
@dangerass1982
@dangerass1982 3 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Thank you very much for the response. I'm gonna jump right into that playlist.
@johannhugo6563
@johannhugo6563 4 жыл бұрын
Question from a newbie: In function handleForm(ev), where does the parameter "ev" come from ?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
The ev variable holds the event object passed from the Event Listener created with addEventListener(). Every function that is called from an event listener will have the event object automatically passed in. Here is my playlist of videos about Events in JS - kzbin.info/www/bejne/e5K1o6CFqbWMiq8
@johannhugo6563
@johannhugo6563 4 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3Thanks a lot. Best EventListener tutorial I've seen.
@raba650
@raba650 Жыл бұрын
Need to send form input fields with a file too using formData. The express server gets an empty object in req.body & req.file is undefined.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
these might help you: kzbin.info/www/bejne/gKWuepanj8l_gq8 kzbin.info/www/bejne/q5OrepSvf7Cbl8U
@robitops1547
@robitops1547 3 жыл бұрын
Why need Request() Object, fetch( url, { method: 'post', headers: {'Content-Type': 'application/json'}, body: JSON.stringify( {json: 'data'} }) is isn't enough ? How Can I send as bellow to NodeJS server, and get [ console.log( req.body) ] my form has image too. const formData = new FormData( this.form ); const urlSearchParams = new URLSearchParams( formData ); console.log( urlSearchParams.toString() ); I am little bit confused.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
You *can* write your fetch calls like that but it is being converted into the Request, Headers, and Body objects. It is rare to build any site where you only have one fetch request. So, by using the proper objects and their methods to add or change values you get a much more manageable codebase. URLSearchParams is really intended to be used for working with the QueryString. I wouldn't pass a FormData object to the URLSearchParams. A FormData object can be passed directly to the fetch( ) method as the value for the body parameter. { method: 'POST', body: formData } The FormData object is capable of handling files too, images or other.
@aleksandr2245
@aleksandr2245 2 жыл бұрын
8:10 but why it's async? it's sync iterator isn't it? And await in front of convertFD2JSON won't do anything with iterator in it, even if it was async, in this case we should use something like for await instead of for...of loop Thank you for your great videos!
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
The pinned comment addresses this.
@aleksandr2245
@aleksandr2245 2 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Oh, didn't notice, sorry about that!(
@barungh
@barungh Жыл бұрын
let objet = Object.fromEntries(fd) I think, now we can use this syntax to get an object from form entries
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
There is a FormData entries( ) method to do that.
@barungh
@barungh Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Wow! I was looking for such method related to FormData , didn't find, may be I will look again ... Thank you so much
@ganeshbalajiradhakrishnan923
@ganeshbalajiradhakrishnan923 3 жыл бұрын
could jsonify() work instead of creating another function?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
jsonify? The content of my convertFD2JSON function doesn't have to be in a separate function but it the type of code that you would normally put in its own function so you could reuse it.
@antoniosalzano5253
@antoniosalzano5253 4 жыл бұрын
- i can use also a server like xampp? - i must use the terminal, i don't know what is it ecc. :( ? - if my local host is 5500 it's okay? Sorry for my 0 knowlege (p.s i'am italian, so it's a bit difficult do understand)
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
FormData object can be used with any web server or server-side programming language.
@gamersoul1098
@gamersoul1098 3 жыл бұрын
hey how did you create that server can you suggest any tutorial please
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
The file is in the code Gist linked to in the description. I have a play list about server-side NodeJS and another on Express. Here is a tutorial from the NodeJS playlist explaining how it was built - kzbin.info/www/bejne/i36uhGmpqp17h8U
@gamersoul1098
@gamersoul1098 3 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 thank you so much sir
@soniablanche5672
@soniablanche5672 Жыл бұрын
You probably should be using URLSearchParams instead of FormData if you're only sending text. multipart/form-data encoding is much bigger than urlencoded so you'll be saving bandwidth and server parsing time.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
Except you shouldn't send anything sensitive through querystring with GET. FormData will run with POST.
@soniablanche5672
@soniablanche5672 Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 My previous message got deleted for some reason. You can use URLSearchParams in a post body and set the content-type to urlencoded (this probably got my message deleted because the actual content-type has 3 W in it lol). That's actually the default behavior of a when doing a POST request
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
@@soniablanche5672 yes. And FormData is the Javascript representation of that
@soniablanche5672
@soniablanche5672 Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 No, FormData uses the multipart/form-data encoding not urlencoded. From MDN: The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
@@soniablanche5672 sorry that is what I was referring to. The multipart/formdata encoding equivalent for a posted form in Javascript
@m3hdim3hdi
@m3hdim3hdi Жыл бұрын
is formdata still used or there is something better?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
Formdata is still used
@huzaifashaikh6384
@huzaifashaikh6384 3 жыл бұрын
sir can u please help I have done exactly as you have told but my request.body is empty object
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
If your FormData object is empty then you missed a step somewhere.
@huzaifashaikh6384
@huzaifashaikh6384 3 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 sir actually I am trying to add files so when I send the form data object to the server its empty so I tried doing it by sending it as the json request then parsing it in the server as u have told but the req body only contains the string fields of the form but only empty objects for file fields
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
@@huzaifashaikh6384 To attach the files you have to use POST not GET as the method. kzbin.info/www/bejne/gKWuepanj8l_gq8
@God4Short
@God4Short Жыл бұрын
Hello.. How to clear the form data?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
Just set the variable equal to null.
@amitsolanki9363
@amitsolanki9363 Жыл бұрын
How can i formData with input file
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
More about FormData object - kzbin.info/www/bejne/b57LqqJnrLZ6m6s Uploading files with fetch and FormData - kzbin.info/www/bejne/gKWuepanj8l_gq8
@jimshtepa5423
@jimshtepa5423 Жыл бұрын
what is the type of formdata?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
It is its own type
@jimshtepa5423
@jimshtepa5423 Жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Understood. thank you. what is the best way to parse form data on the server? i.e. is there any method on `request` object such as `json()` or `text()` that extracts content of the body when the type is formdata?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
@@jimshtepa5423 server side is very different syntax, even with NodeJS
@varunsharma6637
@varunsharma6637 3 жыл бұрын
Would have been better if it weren't precoded!
@sabuein
@sabuein 2 жыл бұрын
Thank you.
Fieldsets and Legends in HTML and CSS
13:55
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 14 М.
Fetch, CORS, and Cookies
37:44
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 21 М.
🤔Какой Орган самый длинный ? #shorts
00:42
Incredible magic 🤯✨
00:53
America's Got Talent
Рет қаралды 66 МЛН
Became invisible for one day!  #funny #wednesday #memes
00:25
Watch Me
Рет қаралды 55 МЛН
Save user form input data in a JavaScript object
7:10
OpenJavaScript
Рет қаралды 38 М.
Efficient ES6 async await with fetch
8:22
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 15 М.
HTML5 URL and SearchParams Objects
10:08
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 5 М.
Sending AJAX Form Data to the Server with fetch
14:54
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 17 М.
Register and Login Full Lifecycle with NodeJS
27:11
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 10 М.
JavaScript Pro Tips - Code This, NOT That
12:37
Fireship
Рет қаралды 2,5 МЛН
Dependency Injection, The Best Pattern
13:16
CodeAesthetic
Рет қаралды 762 М.
7 ways to deal with CSS
6:23
Fireship
Рет қаралды 1,1 МЛН
🤔Какой Орган самый длинный ? #shorts
00:42