Sending a form using the FormData object – JavaScript Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this tutorial so today i'm going to be focusing on how you can optimize the sending of a form with javascript by making use of the native form data object and this includes for forms that have a file input on them so to create a new form data object in javascript you use the new operator before calling the form data constructor and this is going to return a new object of typeform data which is currently empty so in a few moments i'll show you how to send form data inside the new form data object but first let me explain what a form data object actually is so you may already be aware that you can send form data using html alone you don't necessarily need javascript and with html you do that by adding an action attribute to the form and specifying where the data is going to be sent and then if you include the method post the data is going to be sent in the body of the request so there are quite a few reasons why you might prefer using javascript over relying on html for form submission first of all when you're using javascript it prevents a page refresh second you can do more detailed form validation with javascript and third you can more easily edit the data payload that you are sending now what the form data object in javascript does is it does the same work as a form in html when you click submit it's just a way to prepare the form data for sending in javascript instead so because i'm going to rely on javascript for sending this data i can get rid of the attributes on the form now in javascript i've already selected my form so what i want to do next is add an event listener to it listening out for the submit event on that form so this button of type submit will trigger that event and then when that occurs this associated function will fire and what i'm going to do is to create the form data here using the form data object but what i need to do here before i do any form handling is to prevent the default behavior of the page refreshing when i submit the form which is what html wants to do so i'm able to prevent that behavior by calling the prevent default method on the event object now there is a really easy way that you can get all of the form data inside the form data object without having to select all of the inputs individually and that is to pass the form into the parentheses when you create the new form data object now if you want to check the contents of a form data object before you post it you can't actually do that by console logging the form data object directly to the console you need to use an iterative method to access its contents so inside the form data object the form data is stored in an array of arrays where in each nested array there are two values the first one is the name that you give to each item in your form and the second is the value that the user enters or in the case of the file input is going to be the file itself now the input i still need to add a name to that so i'll call that file now the name attribute is very important if you don't set the name attribute for an item in your form it won't be included in the form data object you could still append it to the form data object manually later on but using the code as it is down below where i'm just passing in the form to the form data constructor it wouldn't be included in the data object that this prepares here now given the data structure of an array of arrays you can access the data in the form data object using some kind of iterative method so here i'm going to create a for of loop so i'm iterating through form data and the first thing i want to do in the loop here is log the first element in the nested array to the console and after that i want to log the second one so the first one is going to be the key for each item in the form and the second one is going to be the value that the user has entered so let's see this information printed out in the console now of course i have to enter some values here to be able to submit the form i'll select a file as well and now you can see that loop is printing the contents of the form data object to the console so in the console.log we're getting the name which is the key for this bit of data which was the name attribute in the html for this item and also the value that i just entered and we see the same in the second and the third console log and in the final console log you see that the file that i attached was also successfully integrated into the form data object so all of the form data in the form it's been attached to the form data object without me having to select individually each of the items in the form now if you're happy with the contents of the form data object you might want to send it to the server so i'm going to be using fetch to do that you could use a different method and i'm going to be sending it to a test endpoint that sends back in the response the request i make so i can see what i actually sent to the server so the name of this is http bin dot org forward slash post and to make a post request in fetch you have to specify in an options object in the second position that that's what you want to do so you set the method to post and there's also going to be a payload so you set that as the value of the body property and a really nice feature of sending a form data object as the payload is that you don't have to set any headers on the request this is done for you automatically now all that's left to do is to handle the result so you can access the result of a fetch request using then syntax because fetch is promise based what you get back with a fetch request first of all is a readable stream so in order to be able to access the response you get back you need to read that by using the json method and then in the next then statement you have available to you the actual response object itself so i'll log that to the console now let's see what kind of response we get back from the test endpoint so if it's successful we should get back all of the data we send to it in the response so i'll enter some more data here and include a file and let's see what we get back so first of all we're getting what we logged to the console and here is the response we're getting back from the server now now in terms of the payload you can see already on the form property that all of the form data excluding the file is included here so the name the email and the message and on the files property this contains the image that we sent so using the form data object you can prepare a form data payload to send in this way and it is in no way dependent upon the method that you use to make the http request so i'm using fetch here but you could also do this with axios or ajax you just need to make sure that the form data object is in the payload position for the method that you are using now sometimes you might want a little bit more control over creating the form data object than you get by just passing in the form to the form data constructor so to show you how to do that i'm going to remove the name attribute from the file input which means it's not going to be added to the form data object when i call the constructor and instead i'm going to append it to the form data object manually first thing to do is to give a key to this particular entry so i'm going to give this a key of image the next thing to enter is the value for the entry itself so that's going to be the file in my form i still need to select it so i'll select it using query selector it has an id of file now to access the file that exists on that element i need to access the files property and the files are stored there in an array so there's only one file that the user can upload so of course it's going to be in index position 0 and optionally you can specify the file name under which you'd like the file to be saved on the server so in this case i could say image.jpg so if i wanted to include an id i could create a key like that and then enter the value in the second position so now when i send this off to the server you should see the additional string data as well as the file even though i've removed the name attribute from the input element in the form meaning that it wasn't automatically attached so here you see the string and the file is also included there now finally for this tutorial you may sometimes find yourself in a situation where the server expects json data so it doesn't accept the form data object it wants you to convert it to json first so i'm going to comment out the manual editing of the form data object and actually just remove the file input entirely from the form and that is because if you're sending json then you can't stringify the file so this technique works just for string of fireball data so the first thing to do is to convert that array of arrays inside the form data object to the javascript object so you can do that using object from entries and passing in the form data object to it and now i need the result of that because what i'm going to do next is to convert the javascript object that i've created from that array of arrays into a json objects so you can do this by calling json.stringify it's going to stringify the javascript object you pass that in which is res and this is going to be the new json payload so i will log the payload to the console so you can see it before it's sent off now a couple of changes in the request the payload is no longer form data but the new payload object that i've created so because the payload is no longer a form data object i have to set the headers manually on this request so to set headers on a fetch post request you specify a headers property and inside there you can enter the headers that you want so i will enter a content type and i'll set that to application json now let's take a look at the result of this modified request so with this json payload so the first thing being logged to the console it's the json object which is just a stringified javascript object then i'm getting back the data i entered and here's the response from the server which is just sending back to me what i sent to it so the json object i sent it's on this data property here and as you can see it's in the same format as the json string i created so that's the way you can use the form data object to extract data from a form and then convert its payload into json format so that is it for this tutorial on using the form data object to send form data in javascript i hope you found it useful if you did please consider hitting the like button down below this video and if you'd like to see more content like this don't forget to subscribe to the channel
Info
Channel: OpenJavaScript
Views: 32,289
Rating: undefined out of 5
Keywords:
Id: EnWqnyUZ65Y
Channel Id: undefined
Length: 13min 9sec (789 seconds)
Published: Thu Sep 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.