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
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.
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.
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!
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!!
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.
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 ;)
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
. 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
. 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 ^^_
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.
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!
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.
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
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" ..}
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.
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.
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.
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.
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.
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"
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.
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. ua-cam.com/video/7EKebb4VUYQ/v-deo.html
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?
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.
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 - ua-cam.com/video/EaRrmOtPYTM/v-deo.html
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.
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 - ua-cam.com/video/UMKS6su8HQc/v-deo.html
@@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 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?
- 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)
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 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 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".
. 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
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
Hey, thank you for the clarification there, my confusion has been vanished 👍👍👍. Im a bit confused earlier..
Thank you
thanks for the clarification, Steve, was stuck at this point...
great channel, btw!
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.
my best professor all time i watched your all javascript tutorial
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.
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!
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!!
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.
Excellent tutorial. Your voice is so soothing.
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 ;)
Make sure you have a look at the jQuery rehab playlist.
Yes, saw that and have watched a couple already.
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
me: Fetch
formData: empty
me: fetch again
formData: empty
me: :(
Steve: add a name attribute
me: :)
. 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
Quick tip: For converting formdata to an Object use Object.fromEntries(formDataObject)
Thanks for mentioning that.
Excellent demonstration of extraction, and use of Form data. Thanks.
{2022-07-12}}
Very interesting ! I didn't know handling forms could be less exhaustive
Almost makes them fun, right?
Awesome, Steve! Thanks my friend.
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?
Great video 👍👌🤞🙏❤️
. 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 ^^_
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.
Very useful...good to see you back :)
Glad to be back.
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!
The pinned comment addresses this.
@@SteveGriffith-Prof3ssorSt3v3 Oh, didn't notice, sorry about that!(
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.
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
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" ..}
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.
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.
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.
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.
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.
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"
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.
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.
ua-cam.com/video/7EKebb4VUYQ/v-deo.html
@@SteveGriffith-Prof3ssorSt3v3 Thank you very much for the response. I'm gonna jump right into that playlist.
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?
It's not needed. Brain fart. Was thinking about fetch... promises... for await of when doing the conversion.
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.
these might help you:
ua-cam.com/video/JtKIcqZdLLM/v-deo.html
ua-cam.com/video/ubHIayJKhac/v-deo.html
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.
Yes. The FormData object is how I attach files to the Request object to upload them. - ua-cam.com/video/JtKIcqZdLLM/v-deo.html
Question from a newbie: In function handleForm(ev), where does the parameter "ev" come from ?
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 - ua-cam.com/video/EaRrmOtPYTM/v-deo.html
@@SteveGriffith-Prof3ssorSt3v3Thanks a lot. Best EventListener tutorial I've seen.
could jsonify() work instead of creating another function?
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.
hey how did you create that server can you suggest any tutorial please
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 - ua-cam.com/video/UMKS6su8HQc/v-deo.html
@@SteveGriffith-Prof3ssorSt3v3 thank you so much sir
sir can u please help I have done exactly as you have told but my request.body is empty object
If your FormData object is empty then you missed a step somewhere.
@@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
@@huzaifashaikh6384 To attach the files you have to use POST not GET as the method. ua-cam.com/video/JtKIcqZdLLM/v-deo.html
Hello..
How to clear the form data?
Just set the variable equal to null.
Amazing, informative and detailed video as always Steve, thank you for making it. lol @ your I love spam, checkbox joke.
Nice tutorial. But I have a question,
Why you added an await to call non-promised function?
Brain fart. Was thinking about fetch... promises... for await of when doing the conversion.
let objet = Object.fromEntries(fd)
I think, now we can use this syntax to get an object from form entries
There is a FormData entries( ) method to do that.
@@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
How can i formData with input file
More about FormData object - ua-cam.com/video/9mhyo1wQGeI/v-deo.html
Uploading files with fetch and FormData - ua-cam.com/video/JtKIcqZdLLM/v-deo.html
what is the type of formdata?
It is its own type
@@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?
@@jimshtepa5423 server side is very different syntax, even with NodeJS
- 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)
FormData object can be used with any web server or server-side programming language.
You should use a mascot, or even better, a puppet for entertainment value.
Thank you
is formdata still used or there is something better?
Formdata is still used
great, you save my wasted time!! Thanks!!
Very good tutorial
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.
Except you shouldn't send anything sensitive through querystring with GET. FormData will run with POST.
@@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
@@soniablanche5672 yes. And FormData is the Javascript representation of that
@@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".
@@soniablanche5672 sorry that is what I was referring to. The multipart/formdata encoding equivalent for a posted form in Javascript
I so much much your videos thanks alot, i kept on getting an empty object when sending to a node backend
. 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
. this was suppose to be on the next tuts , hahaha
Thank you sir!
prof3ssorSt3v3 ♥
Thank you.
Would have been better if it weren't precoded!
Thank you.