Тёмный

Using FormData Objects Effectively 

Steve Griffith - Prof3ssorSt3v3
Подписаться 101 тыс.
Просмотров 37 тыс.
50% 1

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...

Опубликовано:

 

30 апр 2020

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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.
@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!!
@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.
@kevinrayparas3094
@kevinrayparas3094 4 года назад
my best professor all time i watched your all javascript tutorial
@ms365developer3
@ms365developer3 4 года назад
Excellent tutorial. Your voice is so soothing.
@pauloramos7032
@pauloramos7032 3 года назад
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 3 года назад
Make sure you have a look at the jQuery rehab playlist.
@pauloramos7032
@pauloramos7032 3 года назад
Yes, saw that and have watched a couple already.
@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
@Colstonewall
@Colstonewall 4 года назад
Awesome, Steve! Thanks my friend.
@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
@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?
@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?
@jangidpulkit9763
@jangidpulkit9763 2 года назад
Thank you sir!
@mohamedatef97
@mohamedatef97 2 года назад
Great video 👍👌🤞🙏❤️
@Pareshbpatel
@Pareshbpatel 2 года назад
Excellent demonstration of extraction, and use of Form data. Thanks. {2022-07-12}}
@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.
@RedEyedJedi
@RedEyedJedi 3 года назад
Amazing, informative and detailed video as always Steve, thank you for making it. lol @ your I love spam, checkbox joke.
@nextleveltech267
@nextleveltech267 Месяц назад
Thank you
@ContraHacker1337
@ContraHacker1337 2 года назад
Thank you.
@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. - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-JtKIcqZdLLM.html
@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 ^^_
@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.
@zimani7g473
@zimani7g473 4 года назад
prof3ssorSt3v3 ♥
@sapnadorbi9142
@sapnadorbi9142 4 года назад
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 4 года назад
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.
@nChauhan91
@nChauhan91 Год назад
Quick tip: For converting formdata to an Object use Object.fromEntries(formDataObject)
@SteveGriffith-Prof3ssorSt3v3
Thanks for mentioning that.
@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.
@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. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-7EKebb4VUYQ.html
@dangerass1982
@dangerass1982 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 Thank you very much for the response. I'm gonna jump right into that playlist.
@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"
@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.
@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 - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-EaRrmOtPYTM.html
@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
these might help you: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-JtKIcqZdLLM.html ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-ubHIayJKhac.html
@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
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.
@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.
@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.
@tubeviewerification
@tubeviewerification 4 года назад
You should use a mascot, or even better, a puppet for entertainment value.
@m3hdim3hdi
@m3hdim3hdi Год назад
is formdata still used or there is something better?
@SteveGriffith-Prof3ssorSt3v3
Formdata is still used
@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 - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-UMKS6su8HQc.html
@gamersoul1098
@gamersoul1098 3 года назад
@@SteveGriffith-Prof3ssorSt3v3 thank you so much sir
@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. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-JtKIcqZdLLM.html
@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!(
@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
@God4Short
@God4Short Год назад
Hello.. How to clear the form data?
@SteveGriffith-Prof3ssorSt3v3
Just set the variable equal to null.
@amitsolanki9363
@amitsolanki9363 Год назад
How can i formData with input file
@SteveGriffith-Prof3ssorSt3v3
More about FormData object - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-9mhyo1wQGeI.html Uploading files with fetch and FormData - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-JtKIcqZdLLM.html
@barungh
@barungh Год назад
let objet = Object.fromEntries(fd) I think, now we can use this syntax to get an object from form entries
@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
@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
@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
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
@@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
@@soniablanche5672 sorry that is what I was referring to. The multipart/formdata encoding equivalent for a posted form in Javascript
@jimshtepa5423
@jimshtepa5423 Год назад
what is the type of formdata?
@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
@@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
Просмотров 14 тыс.
JavaScript Fetch with Request and Headers Objects
16:26
ПАЛОЧКА В НОС (СЕКРЕТ)
00:40
Просмотров 93 тыс.
Brawl Stars Animation: PAINT BRAWL STARTS NOW!
00:52
Просмотров 3,4 млн
БИМ БАМ БУМ💥
00:14
Просмотров 3,6 млн
HTML Forms and JavaScript
26:20
Просмотров 74 тыс.
Sorting Complex Objects in JavaScript
10:29
Просмотров 21 тыс.
Fetch, CORS, and Cookies
37:44
Просмотров 21 тыс.
HTML5 URL and SearchParams Objects
10:08
Просмотров 5 тыс.
React 18 Tutorial - FormData API
11:12
Просмотров 4,3 тыс.
Turning Form Data to CSV files with JavaScript
26:13
Efficient ES6 async await with fetch
8:22
Просмотров 15 тыс.
Sending AJAX Form Data to the Server with fetch
14:54
ПАЛОЧКА В НОС (СЕКРЕТ)
00:40
Просмотров 93 тыс.