Using FormData Objects Effectively

Поделиться
HTML-код
  • Опубликовано: 2 ноя 2024

Комментарии • 102

  • @SteveGriffith-Prof3ssorSt3v3
    @SteveGriffith-Prof3ssorSt3v3  4 года назад +16

    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 года назад +1

      Thank you

    • @viniciusmelo1930
      @viniciusmelo1930 2 года назад

      thanks for the clarification, Steve, was stuck at this point...
      great channel, btw!

  • @trophieboi1820
    @trophieboi1820 4 года назад +2

    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.

  • @kevinrayparas3094
    @kevinrayparas3094 4 года назад +2

    my best professor all time i watched your all javascript tutorial

  • @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!

  • @allanregista4422
    @allanregista4422 4 года назад +3

    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.

  • @Gollumfili
    @Gollumfili 3 года назад

    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 4 года назад

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

  • @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

  • @ms365developer3
    @ms365developer3 4 года назад +1

    Excellent tutorial. Your voice is so soothing.

  • @rubenvandevelde555
    @rubenvandevelde555 3 года назад +10

    me: Fetch
    formData: empty
    me: fetch again
    formData: empty
    me: :(
    Steve: add a name attribute
    me: :)

  • @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 ;)

  • @42HUE
    @42HUE 3 года назад +1

    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?

  • @Pareshbpatel
    @Pareshbpatel 2 года назад

    Excellent demonstration of extraction, and use of Form data. Thanks.
    {2022-07-12}}

  • @yannicknana
    @yannicknana 4 года назад

    Very interesting ! I didn't know handling forms could be less exhaustive

  • @mackynikat8833
    @mackynikat8833 3 года назад

    . 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

  • @Colstonewall
    @Colstonewall 4 года назад +1

    Awesome, Steve! Thanks my friend.

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

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

  • @nChauhan91
    @nChauhan91 2 года назад +2

    Quick tip: For converting formdata to an Object use Object.fromEntries(formDataObject)

  • @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. - ruclips.net/video/JtKIcqZdLLM/видео.html

  • @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 года назад +1

      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.
      ruclips.net/video/7EKebb4VUYQ/видео.html

    • @dangerass1982
      @dangerass1982 3 года назад +1

      @@SteveGriffith-Prof3ssorSt3v3 Thank you very much for the response. I'm gonna jump right into that playlist.

  • @mohamedatef97
    @mohamedatef97 2 года назад

    Great video 👍👌🤞🙏❤️

  • @nextleveltech267
    @nextleveltech267 4 месяца назад +1

    Thank you

  • @SzypkieJapko
    @SzypkieJapko 24 дня назад

    Very good tutorial

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

  • @robitops1547
    @robitops1547 4 года назад

    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  4 года назад

      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.

  • @mackynikat8833
    @mackynikat8833 3 года назад +1

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

  • @iwswordpress
    @iwswordpress 4 года назад

    Very useful...good to see you back :)

  • @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 года назад +1

      It's not needed. Brain fart. Was thinking about fetch... promises... for await of when doing the conversion.

  • @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"

  • @4541047
    @4541047 4 года назад

    Nice tutorial. But I have a question,
    Why you added an await to call non-promised function?

  • @hernangarcia77
    @hernangarcia77 3 года назад

    great, you save my wasted time!! Thanks!!

  • @raba650
    @raba650 2 года назад

    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  2 года назад

      these might help you:
      ruclips.net/video/JtKIcqZdLLM/видео.html
      ruclips.net/video/ubHIayJKhac/видео.html

  • @tubeviewerification
    @tubeviewerification 4 года назад +1

    You should use a mascot, or even better, a puppet for entertainment value.

  • @RedEyedJedi
    @RedEyedJedi 3 года назад

    Amazing, informative and detailed video as always Steve, thank you for making it. lol @ your I love spam, checkbox joke.

  • @jangidpulkit9763
    @jangidpulkit9763 3 года назад

    Thank you sir!

  • @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 - ruclips.net/video/EaRrmOtPYTM/видео.html

    • @johannhugo6563
      @johannhugo6563 4 года назад

      @@SteveGriffith-Prof3ssorSt3v3Thanks a lot. Best EventListener tutorial I've seen.

  • @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!

  • @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 - ruclips.net/video/UMKS6su8HQc/видео.html

    • @gamersoul1098
      @gamersoul1098 3 года назад +1

      @@SteveGriffith-Prof3ssorSt3v3 thank you so much sir

  • @ganeshbalajiradhakrishnan923
    @ganeshbalajiradhakrishnan923 4 года назад

    could jsonify() work instead of creating another function?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 года назад

      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)

  • @ade-ajayiabolaji4005
    @ade-ajayiabolaji4005 3 года назад

    I so much much your videos thanks alot, i kept on getting an empty object when sending to a node backend

  • @m3hdim3hdi
    @m3hdim3hdi Год назад

    is formdata still used or there is something better?

  • @huzaifashaikh6384
    @huzaifashaikh6384 4 года назад

    sir can u please help I have done exactly as you have told but my request.body is empty object

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 года назад +1

      If your FormData object is empty then you missed a step somewhere.

    • @huzaifashaikh6384
      @huzaifashaikh6384 4 года назад

      @@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  4 года назад

      @@huzaifashaikh6384 To attach the files you have to use POST not GET as the method. ruclips.net/video/JtKIcqZdLLM/видео.html

  • @sabuein
    @sabuein 2 года назад

    Thank you.

  • @zimani7g473
    @zimani7g473 4 года назад

    prof3ssorSt3v3 ♥

  • @barungh
    @barungh 2 года назад

    let objet = Object.fromEntries(fd)
    I think, now we can use this syntax to get an object from form entries

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 года назад

      There is a FormData entries( ) method to do that.

    • @barungh
      @barungh 2 года назад +1

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

  • @God4Short
    @God4Short 2 года назад

    Hello..
    How to clear the form data?

  • @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

  • @amitsolanki9363
    @amitsolanki9363 Год назад

    How can i formData with input file

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  Год назад +1

      More about FormData object - ruclips.net/video/9mhyo1wQGeI/видео.html
      Uploading files with fetch and FormData - ruclips.net/video/JtKIcqZdLLM/видео.html

  • @mackynikat8833
    @mackynikat8833 3 года назад

    . 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 3 года назад

      . this was suppose to be on the next tuts , hahaha

  • @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 4 года назад

    Would have been better if it weren't precoded!

  • @ContraHacker1337
    @ContraHacker1337 2 года назад

    Thank you.