POST Form Data With JavaScript Fetch API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
everyone in this video we will get the data from a form and submit the data to a server with the fetch api in javascript okay so here in the html we have a form it has three inputs one for the username one for the password and a checkbox for the terms and conditions right fairly standard and a button that if you click on it will submit the form right so that looks like this in the browser it has no styling username password they have placeholders here checkbox and i can submit this okay now what we want is that when the user has filled out the form and submits the form we want to send the data to a server but first we have to get the data from the form right so here i have created these script tags so in here i can write javascript so first we need to select the form right i will call that form element or form l i can use document.queryselector and it has a class of form so i can select it like this right so i like to append l to my variable names if there is a reference to an html element stored in that and then we want to listen for the submit event on that html element and when that event occurs this function will be run when you have a form right so if i fill this out and i submit this you can see this the page sort of refreshes itself and this is because the when you submit a form there is some default behavior so maybe you remember that you know if you've been coding for a bit longer that these forms used to have an action attribute right so here you would specify um you know some kind of url and this is actually where the forum data would be sent to in the past so when you submit a form the browser will automatically send it to this address here and that's still what it's trying to do here right now these days we don't want that we don't want that default behavior we want to do it ourselves in our javascript so manually you could say so we don't want that default behavior so what we actually get with every with every event handler as this is called we're handling the submit event here with this function the browser always gives us an event object right with some information about the event that just happened and one of the things that we can do with this is say event dot prevent default right so we don't get that default behavior right so now when i submit here nothing happens right which is actually what we want but now we actually want to get the data from the form uh the best way to do this is simply with uh well as follows so i'll create a new variable form data and we can actually use new form data and we need to pass a reference to a form so that's what we have in form l so what this will do is it will take all the data from this form the username the the password the terms and conditions checkbox and it will put that in an object that we get here right and the reason that this exists is to make it easier for us to work with the form data right you can imagine it would be a lot of work if we had to select each of these elements individually and imagine if you have a very large form and you had to select all of the inputs manually so instead we can use new form data and only pass the form element or the reference to it and now we get an object that makes it very easy for us to work with the form data so i can say for example show me the value for user name right form data.get let me quickly log this now if i submit this we see the value for the username we can also set it manually so we can override what the user wrote i can i can even add something append or delete right i can do all sorts of things right but it does not prepare the data yet for sending it to a server right we need to do an additional step for that we want to send data to a server with the fetch api so let's actually see how this how that would look like so we can use fetch and then here we'd have we have to specify the url to which we want to send the data and i'm going to use a service called rackrest.in this is a surface we can use to just do some quick tests the rest of the url is like this right so usually you have the word api in an external api and then the name of the resource right so in this case we want to post to the user's resource right let's imagine that this form is some kind of register form right so we want to create a new user now this is what you would have for a get request but we want a post request so we have to specify some additional things the first one being the method right the default is actually get but here we want post now when you send data to a server you have to let the server know what the format of the data will be and we do that with headers i can say headers and the only header actually only one header needs to be specified is content type and you know usually it's json right these days we usually send data in json format json is in the application category now by the way you cannot write object keys like this with a hyphen so people typically wrap this in quotation marks most of the time you're actually gonna exchange data with a server in json format however when you work with forms like we are working here the typical format is actually um a query string and this is actually also called xwww form url encoded right so this is the more typical format for submitting form data and that's what we will use here now if your form has file upload so maybe the users can upload a an image or a video you may want to use multi-part form data right so if you have large binary files this is the content type you want to use but we will use this one and now in body we have to pass the actual data that we want to submit and so here we have our forum data and now we need to turn that into the format this format and so it needs to be url encoded format and it will basically be a big query string so what is a query string well maybe you've seen this before in a url so it's like username is john and password is you know something secret and then with a checkbox by the way it's encoded with on or off the checkbox here has a name of terms conditions terms conditions is on right if it's checked right so this would be a query string right and the question mark here is to separate the query string from the path right so a query string is just a bunch of key value pairs right so how do we get form data here into that format so we'll say cons data well we can actually use new url search params and we can actually give the form data object and it will create that query string or this format out of that right so now this will be what's called url encoded so we put that in data and that's actually what we want to send right so we're not sending it as part of the url and so especially with passwords you shouldn't send that as part of the url right we're sending it as part of the body right this will be the payload and also uh we actually don't have to specify the headers here right i just wanted to show you this to so you could see how that would work but if we leave this off the browser can still correctly infer what the format is and it will actually automatically set the content type header for us right so we don't have to specify that here all right so this is enough to send data now maybe this server sends back a response like a success message or you know if something goes wrong maybe an error message so i have a whole video on how the fetch api works and how you could properly structure it definitely check it out after this video here we'll just do something we'll keep it pretty basic so we get some kind of response and if the server sends back response it will be in json format which we will parse here and then we get the actual data here we could log that if the network request or response does not arrive we will actually well the promise from fetch here it's promised based will actually reject as it's called and we will go in the catch block here right so we can make this more sophisticated so definitely check out the fetch api video we can also use async await these days but uh we'll keep it basic here all right so then i'm gonna save here so now we're gonna check to see if this works my username is blah blah my password is secret i'm gonna check the box here and i'm gonna click submit and we actually get something back although we are not super interested in that it does confirm that everything went all right because this is actually what that service does when you submit something so it actually gives it an id and create an ad and we can also check the network tab to double check so here we can actually see users so we see general information response headers request headers right so you can see content type has been set for us automatically by the browser the payload right so the data that we actually sent this is indeed what we sent right so that is how you can get data from a form and submit it with the fetch api in javascript alright that was it for this video hope that you learned a lot now if you like the video and you want to become a professional modern javascript developer then definitely check out the full course it has two beautiful real worlds projects that we built from scratch and you will learn much more like fetch and promises and async awaits destructuring the spread operator advanced javascript how to structure or architect your projects modern front-end concepts like components state and rendering and much more it's all in there check it out the link is in the description in any case thanks for watching and i hope to see you soon you
Info
Channel: ByteGrad
Views: 23,201
Rating: undefined out of 5
Keywords: javascript form, js form, js fetch api, fetch api, fetch(), fetch http post, http methods, http post, post form data, js form data, javascript collect form data, javascript fetch, post form data with fetch, formdata, new formdata(), urlsearchparams, new urlsearchparams, new urlsearchparams(), content-type, x-www-form-urlencoded, Content-Type: x-www-form-urlencoded, form submit
Id: fGYQJAlLD68
Channel Id: undefined
Length: 9min 52sec (592 seconds)
Published: Mon Jul 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.