POST form data using Axios API in JavaScript (including a file)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this video tutorial in which i'm going to be showing you how you can use the axios api to send form data in javascript so axios is a third-party library for making http requests under the hood it uses ajax or the xml http requests object and it's promise based the main advantage of using axios is that it has a very simple syntax even simpler than the fetch api so in case you're not already familiar with axios i did make a video showing you how to make get post put and delete requests using it so if you're not familiar you might want to check that out before continuing in this video we're going to be focusing on sending form data in the form of a post request okay so to install axios you can install it from the command line using npm by writing npm install axios if you do want to do it that way axios has an official npm page where there are detailed instructions on how you can install axios locally but in this tutorial just to get up and running really quickly i'm going to be using a cdn link posting that in the head of my html document and then the axios library will be available in my script now i did test before this tutorial the js delivers cdn here this doesn't seem to be working this is probably just a temporary problem but so for this tutorial i'm going to be using this unpackaged cdn here so in my document i'm going to paste that in the head of my document okay so this is the form element that i'm going to be posting in this tutorial it has three input elements two of type text and one is of type file so i'll be showing you how you can post not only text data as in the value that the user enters but also a file and in this case it's going to be of type image but it could be any other type of file and if you're creating a form don't forget to include the type attribute and set that to submit so that when the user clicks the button it will trigger a submit event on the entire form okay so let's move on to the javascript now and how we can get this data out of the form once it's completed and send it to a http endpoint so the first thing you want to do of course i'll just move this up a little bit is to select the form so i'll select that by its id which is form okay now what i'm going to do is add an event listener to the form and i want to listen out for a submit event now the submit event is occurring when the user clicks the button not on the form and that's occurring because the button has the type submit there so i'm listening out for this submit event on the form and when that occurs it's going to fire this associated function now the very first thing i want to do is to make sure that the form is not submitted automatically by html because this will refresh the page and i want to control the submission process in javascript so the way that i can prevent that is on the available event object that i have here i say e dot prevent default so this is preventing the default behavior of html submitting the form okay so what you want to do next is to take the data that is available in the form and store it in a form data object so the form data object it's a native object in javascript and to create a new one you use the new operator before it and that's going to return an object instance of form data and i'm going to save a reference to that that's going to be form data now the reason you're going to want to use a form data object is because if you store the data available in a form in a form data object then when you make a post request with payload so the form data the headers and the encoding are going to be set for you so you don't have to do much manually at all so it's a good idea to store the data inside a form data object which is just kind of like a container for data available in a form you can put other kinds of data in there but it's really designed for form data especially now an easy way to put all of your form data inside a form data object in one go is to pass in the form inside form data when you're creating it now all of your data from that form will be stored in this reference form data now if you want to see the contents of a form data object you can log it to the console in the following way you create an array and use the spread operator to spread the contents of the form data object into that array now we should be able to see what's been stored inside the form data object in the console so i need to click submit here just to see that and you see there's three arrays inside here and we have first name last name and photo so there's nothing in first name at the moment or last name or photo so if i just write brad pip here and i submit you'll see that this data is now being stored inside the form data object and notice that it's being stored in key value format now there's a little bit of a gotcha to the method i just showed you if i delete the name from one of these inputs so i'll just delete last name and we try that again so i'll just use the same name again you'll see that there's only two bits of data there now first name and the photo so if the input element doesn't have a name it's not going to be stored in the form data object if you pass it in like we did here with new form data and the form in parentheses so an alternative way that you can store data inside the form data object is to append it on an individual basis so if i say here form data dot append now remember it's in key value format so the first bit of information you need to enter here is the key you want to save something under so i removed the last name from the name from the input attribute so that wasn't there now what i need to do is to insert the value for what i'm appending here so i want this to be let's have a look at the id so the id is last name so i can say document dot get element by id and it's last name and then the value should go there so even though there's not a name there now on the input element it should now be working so i'll input the same data as before and you can see that last name is there now so i appended it and it's now on that object you can see it's in a different order now because the first two were added when i created the form data object and last name is now last because that was appended afterwards so in this way if you wanted to you could add data that's not even in the form to the form data object so you could say for example form data dot append so i'll just say id here and i'll enter a number there now when i go back to the form you see now that data that wasn't even in the form is in the form data object so this append method gives you some flexibility in terms of adding data that wasn't even in the form in the first place okay so now for the posting of the form data using axios so i have available to me axios because i included the cdn link in the head of my document and i'm going to be calling the post method because i want to post this form data now you need to enter two bits of information here the first one is the url endpoint where you're sending the data to and the second is the payload so we already have the payload that's form data now the endpoint i'm going to be using in this example is a test endpoint that you can also use it's called httpbin.org and i want to make a post request so what this is going to do is it's going to send back the request i sent to me so i can see what it looked like to the server so this is a nice way of making http requests and getting some diagnostic information back okay now we're ready to handle the result of this post request so axios is promise based if it's successful then it's going to fire the then method inside the then method as a parameter you have available to you res so this is going to be the response if it's successful and we can use it inside this function here so i'm going to console.log res if it's successful if it's not successful for some reason then the catch statement will be triggered and i'll log the error in case there is one as well okay so let's see if it's working now in the browser so i'll enter my text data here and i'm also going to include a file this time and those will be attached to the form data object and i send it and you can see i get the response from the server status 200 letting me know that the post request was successful if i look here it's sending back what i sent to it so you can see the form the data that i sent so it included brad first name the id the last name and it also contains the file the photo that i sent now also if we take a look at the headers you see that these were set for me so if you weren't using a form data object you would have to set some of this manually but using the form data object content type was set to multi-part form data and accepting application json and text planes so this is the reason why it's really useful to use a form data object now just finally i'm using promises syntax in my code here but you might want to use the more modern version async or white so you can easily change this to async await by using the async keyword before the function that's going to be called when the form is submitted now what you do down here is you use a weight before axios and that's going to wait for the response to come back from the server and that's going to be saved in result and then you can just console.log result so this would work but what about the error so the way that you handle that is you do what you're attempting inside a try statement so i just copy and paste that in and then it's followed by a catch statement where you have available to you as a parameter to the error and you can log the error to the console so it's like then in catch but in this case try you're going to try this first and then the catch statement is going to be triggered if it doesn't work out so exactly the same result should be produced here i'm just using async await syntax which is just an alternative syntax for handling promises so if i submit that you see again i get the same result back with the data including the file and the form so that is how you can post form data using the axios api for javascript so i hope you found this tutorial 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: 22,173
Rating: undefined out of 5
Keywords:
Id: r7r45An_Lkc
Channel Id: undefined
Length: 12min 46sec (766 seconds)
Published: Thu Aug 04 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.