POST Form Data as JSON with Fetch API in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will collect data from a form and convert it to Json format and then sent it to a server with a JavaScript and the fetch API okay so here I have a simple HTML file with a form the form has a username a password terms and conditions checkbox and a submit button right so fairly typical you can imagine this is some kind of sign up or register form it looks like this in the browser right so these inputs they have a placeholder so if the user fills out this form and clicks submit we want to send that to the server in Json format right but first we have to collect the data from the form so I have script tags here so in here I can write JavaScript we want to collect the form data when the user clicks on the submit button right so then the form gets submitted so we're going to listen for the submit event on the form element so I can select the form first I like to append L to the variable name if I select an HTML element so then here we're going to attach an event listener so that we can do something when the submit event occurs right so we're listening for the submit event and then this is the function that we want to run when that event occurs right so using the modern Arrow function syntax okay so let's I'm Gonna Save here and I'm gonna check what actually happens right now if we try to submit right so just filling this out okay so that was a weird refresh so right now in the default situation when you have a form and the form gets submitted there's actually sort of a refresh and that's because uh maybe you've seen this before there's also an action attribute on a form right so the default situation is actually that the browser tries to submit the form data to an address that you specify here this used to be how you would submit a form to your server you would specify the the server address here and then the browser would try to go to that page right so that's why you see sort of a refresh so that is still some default behavior and we don't want that default Behavior so what we can do is we actually get an event object here and the browser always gives us gives us an event object when an event has occurred and one of the things we can do with that is we can say event dot prevent default right so we don't want that default Behavior we don't want that weird refresh right so now when I go here and I try to submit nothing happens which is actually what we want right now okay so when the user clicks submit we want to get the data from The Forum right so we want to see the username the password whether the user has checked the checkbox so we could select all of these elements individually and get their value but there's an easier way with a form data so it looks a little bit strange but we can say new form data and then we just pass a reference to the form we very easily get all the data from the form right so now we have an object here form data which makes it very easy to work with the data from the form for example maybe I want to see the value for username right and I'm gonna lock that right so if I save here that's for now my username let's say it's blah blah if I submit now I see the username right so I can also for example set a value to username so I can overwrite what the user wrote I can also delete this particular value I can also append something to the form data right so with form data it just makes it easier for us to work with the form data but it does not give us the format yet in which we want to send it to the server we want to get all the form data and we want to create a Json object out of that right and that's what we will send to the server so let's try doing that how can we how can we get the right format here well let's actually create a normal JavaScript object out of all the Forum data and then when we use fetch right we're going to use the fetch API we will stringify it to Json right so we just want a normal JavaScript object so how can we get that from here well it's a little bit strange but we have to use objects.fram entries and then we pass the form data right so if we log this console.log data right blah blah secret as my password so now what we get is a an object as you can see so we have username blah blah terms conditions is on right so a checkbox when you check it it's actually on if you don't check it it's off password is indeed secret right so now we have this normal JavaScript object right and we're going to convert it to Json in a second we want to send this to a server right we're going to use the fetch API for that so we can write fetch so I'm going to use a surface called request.in we can also get the data from them but we can also submit something to see if it works so the URL is API users okay now we're submitting data so we need a second argument here because it's going to be a post request right the default here is get so if you're just getting data you don't have to specify this but here we want post now when you submit data to a server you also need to let the server know what the format will be we do that with headers well it's only going to be one header which is contented type now we cannot write object keys with a hyphen like this so people typically wrap this in quotation marks and then that will work okay so the content type is going to be Json which is in the application category and then here in body the actual data that we want to send right so that's the data here that we from the form but basically we're going to stringify it that's why this method is called stringify right so now we're taking our normal JavaScript object and it will be converted to Json format right and that will be the body that we send to the server okay so I'm Gonna Save here and then we're gonna check it out I can check this by looking in the network tab okay so I'm gonna fill out the form blah blah Secret I will check the checkbox and I'm gonna submit here when I scroll down here we do see a network request for users so here we can see there has been a post request and the status code is 201 which means resource successfully created which is indeed what we want to do when we have a post request we want to add something to the user's resource we can say payload right this is the data that we sent with the request right which is correct here right and in few Source we can see that the format is indeed Json right you can tell by these quotation marks for the object Keys okay now one other thing with fetch here is you may also want to get a response right or you want to do something with the response so very basic way of dealing with a response we're gonna get a response object here and that's going to be in Json format and we want normal JavaScript so we're going to convert the Json that we get in the response to a normal to normal JavaScript syntax and then here we get the actual data that the server percent back to us so for now we're just gonna lock that it really depends on your on your setup like what do you want to do like what you expect that the server is going to send back maybe just a success message or an error message I have a whole video on the fetcher API I highly recommend you check it out because it goes a little bit deeper into the mechanics of it for example one of the things that could happen with fetch is actually promise based and This Promise will reject as it's called if the request response cycle cannot be completed for example your internet falls out in that case we will go and Dot catch here and we will get an error object which we can log for now but uh this could be you know an easy way of dealing with the response go to the console here and I quickly fill this out again right so we actually do get a response from the server it's actually sending back the object that we sent it but it's actually but now it also added an ID and a created add field but now it also added ID and create and add properties so this is a confirmation that the submission went successfully now there is one problem that can happen by the way if some of your inputs here have the same name right so I have name username here name password name terms and conditions now sometimes you're gonna have multiple checkboxes or select inputs or select fields and they may have the same name in that case when you do this when we create a normal JavaScript object it's not going to take all of them it's only going to take one of them a quick and easy way of solving that is to Simply make these different names right so you could you can just tag on a number like this all right so this was an example of how to take form data turn it into Json and send it to a server 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 world 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 States 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
Info
Channel: ByteGrad
Views: 57,486
Rating: undefined out of 5
Keywords: post form data, fetch api, fetch(), fetch js, fetch javascript, form data js, fetch http post, fetch post, fetch form data, formdata, formdata json, form data json, http post json, convert form data to json, new formdata(), new formdata, html form data to json, fetch post api call, fetch post json, fetch api json, fetch api post
Id: DqyJFV7QJqc
Channel Id: undefined
Length: 9min 25sec (565 seconds)
Published: Wed Jul 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.