AJAX Crash Course (Vanilla JavaScript)

Traversy Media · Beginner ·🛠️ AI Tools & Apps ·8y ago

Key Takeaways

This video covers the basics of AJAX using Vanilla JavaScript, including making requests to local files, external APIs, and PHP files, and handling responses. It also covers topics such as JSON parsing, error handling, and security considerations.

Full Transcript

[Music] hey guys recently I've had a few requests to do a crash course on ajax ajax is an extremely important technology and web development so i thought it would be a good idea so we're gonna talk about what ajax is what it's used for we're gonna go through some slides look at how it works and then we're gonna jump into some code and we're going to experiment a little bit with Ajax and the xhr object alright so before we get started I just want to quickly mention some of my social media links for anybody that wants to follow me and stay up to date with videos and projects udemy courses and so on I also just created a discord chat server that's open to the public it's a place where anyone can go and get help with programming and web development share ideas and so on I pop in daily and chat for a little bit as well all right so what is Ajax it's an acronym for asynchronous JavaScript and XML it's not a language it's not a framework or a library it's simply a set of web technologies to send and receive data from a client to a server asynchronously so it's all done behind the scenes without having to explicitly reload the web page now one thing that's kind of ironic is even though XML is included in the acronym XML is very rarely used in Ajax any more jason has pretty much taken its place that's JavaScript object notation and it's just easier it's faster and it's much more popular so most of the API is if you're working with external api's you're probably going to be working with jason and not xml or maybe both some sometimes these external api's will return both if needed alright and ajax can also just work with plain text so let's take a look at a quick diagram to kind of explain how ajax works so this is the client or the browser and then this is the server this could be your local server or it could be some kind of web api some kind of external API all right now usually when we I work with a server when we make a request to a server from a client we type in the link or we click a link I'm sorry we type in a URL or we click a link and it makes a common request to the server and then the server sends a common response back which includes the headers the web page pretty much just everything we request everything and we get everything well with Ajax what it allows us to to do is it allows us to make requests asynchronously in the background without having to reload or refresh the entire web page all right so if we wanted to just update one little section of text we can do that with Ajax and it's a hell of a lot faster than having to reload the entire page ok and it makes things much more interactive now the way that this works is by making some kind of Ajax call and this can be done with plain JavaScript or it can be done with some kind of library okay it can be done with jQuery or an HTTP library like Axios there's a lot of different ways to do it we're going to basically focus on plain JavaScript all right and I'll talk about that in a little bit but basically the server is going to return data usually in JSON format it could be an XML it could be plain text and this is done this request is done by using the XML HTTP request object okay and I'm going to talk more about this in a minute but we'll make our request it'll do whatever it needs to on the server it may update a database you may have it so that when you you know type something into a form and then you click outside of the form that'll actually make a request and update the database or you may just be fetching some data you'll get it back and you'll do what you want with it you can put it in your web page or whatever it is that you want to do there's just so many different things that you can do with Ajax all right now like I said this happens through something called the XML HTTP request object also called the xhr object and this is actually an API in the form of an object okay and what that means what I mean by an object is it has properties and methods attached to it and this is actually provided by the browsers JavaScript environment so all modern browsers have this API its methods transferred data between client and server or browser and server and it also can be used with other protocols other than HTTP although HTTP is usually what it's used with all right they can also work with data other than XML obviously like I said Ajax is these days more commonly used with Jason all right it can also use plain text so we're going to be examining this object and we're going to look at some of its properties and methods and look at how it works a little bit all right so there's a bunch of different ways to make Ajax calls now just like with everything there's libraries to make things easier as far as the amount of code that you need to write the handlers and things like that now libraries can be great but you should know how to make an actual request using plain old JavaScript you know using the xhr object before jumping into these libraries so that's what we're gonna focus on in this series are not in this series but in this video in this crash course and then towards the end if we have time we'll jump in and we'll look at some of these libraries all right so jQuery is you know you guys know what jQuery is it's a Dom manipulation library it's it's huge as a lot of different things you can do with it I would not suggest using jQuery just for Ajax calls it's it's way it's way too much overkill for that if you are using it anyways in your application or your website then fine but I wouldn't suggest using it just for Ajax calls okay a library like Axios or super-agent these are really nice slim libraries for making HTTP requests and you can make updates and deletes and all kinds of things so these are really nice libraries to work with the fetch API is actually part of the browser it's it's pretty new I know it's fully implemented in Firefox and Chrome I'm not too sure about the others so if someone wants to clarify you know the compatibility with with edge in Safari and these other browsers I'm not really sure I have used it and I do like it I'm just not sure as far as the compatibility goes although I know there are polyfills for and stuff like that prototype is another library I haven't used so I can't say too much about and then of course we have no js' node HTTP but you need to you need to install node and get into that and that's just not part of this of this course here all right so what we're gonna do now is jump in we're going to I'm going to show you how to set up an ajax request we're gonna really look at the xhr object look at some of its methods and properties and I want you to just kind of wrap your head around how Ajax actually works and then if we have time we're gonna look into using some of the libraries as well alright so let's get started alright guys so we're gonna get started now as far as your environment you do need to have some kind of server to work with Ajax you don't want to be just opening your HTML file from you know from windows or from your filesystem now you can you have a lot of different options what we're gonna be doing is using xampp which is it gives us an Apache server it gives us PHP and MySQL on our local machine and if you want to install this you can go to Apache friends org and you can install it if you watch the second video of my PHP front-to-back series it shows you how to install it now the reason I'm using this is because we are going to deal a little bit with PHP towards the end for those videos you will need you will need PHP and xampp gives you that for the first few videos just looking at making requests to to an external API into a plain text file and adjacent file you don't actually need PHP installed and you could use any server you could just use your if you're using vs code you could use live server or something like that but we're just gonna use xampp so i'm gonna go to my c drive and then xampp and then htdocs this is the server folder and I'm just gonna create a folder here called ajax crash and we're gonna creating a I'm going to be creating a bunch of different files in here what I'm gonna do is open this folder up in vs code so htdocs Ajax crash alright and we're gonna create a new file here called Ajax 1 dot HTML we're gonna have about eight different files because we're gonna go through you know loading a plain text file loading Jason loading an external external data loading from a PHP file and then we're gonna look at some of the different libraries as well so hopefully this crash course will be about an hour so I want to keep it around there alright now what we're gonna do is just set up a basic HTML document now I'm using vs code which has Emmet's so I can just do an exclamation and tab and it'll give me this basic HTML layout and I'm just gonna enable word wrap here so you guys can see everything alright and then what I'll do is just let's change the title we'll say Ajax 1 and I just want to give a little description for each file we're going to let's just say I'll say text file because we're just going to fetch a text file asynchronously so we'll save this and then I should be able to go to my local host slash Ajax crash slash Ajax 1 dot HTML alright and you'll see it's going to load that HTML file now what I want to do is I want to create a button to click and then we're gonna create a function that's going to make our Ajax call so let's go ahead and let's create a button I'm gonna give this an ID of let's say button oops so an ID of button and then let's go in here and we'll say get I will just say get text file alright and then what we'll do actually we'll just leave that that's all we'll do for now so we'll save it and we should see a button that says get txt file so let's go ahead and create some script tags right above the ending body tag say script put those tags in there and we want to we want to create an event listener all right because we want to catch the click of this button so what we'll do is we'll say document dot get element by ID okay we gave it an ID of button and you're going to learn if you're new to JavaScript you'll learn quite a bit about you know Dom manipulation and things like that as well so get element by ID button and then we just want to add an event listener so we're going to say dot add event listener we want to listen for a click on this button and once we click we want to run a function called load text okay so now we're going to create that load text function and this isn't going to be like you know a clean-cut application type course we're just we're just messing with the code so that we can see what's going on I'm not trying to create anything pretty or anything like that okay just to let you guys know so let's just do a console dot log here and we'll just say button clicked just so we know that it's actually hooked up so we'll go ahead and click f12 to open up our dev tools make sure you you're on the console and you reload and we click and we get button clicked all right so now let's set up to make an AJAX request so what I'm gonna do is create another file and I'm gonna call it sample dot txt okay so just a simple txt file and we're gonna put some text in here I have Emmet so I'm gonna say larom 50 tab and that'll just give us 50 words of sample text and I'm gonna go ahead and save that and close it all right so we have this sample text file so let's get rid of this console log and the first thing we want to do here is we want to create the xhr object all right and this this file is going to be heavily commented because I want you guys to know what's going on the rest of the files not so much just this one just to kind of explain everything so to create this object we need to create a variable and you'll see this sometimes called request or even HTTP request XML requests I like to call it xhr just keep it short but we're gonna set it to new XML HTTP request okay just like that and that's actually going to be a function so it's going to have parenthesis on the end okay next thing we want to do is decide we need a function to make the request the type of request and what what file or URL we're making it to so we're gonna use the open function so let's say open and this takes in three parameters one is gonna be the type one is going to be the either the URL or the file name and then one is gonna be if it's asynchronous or not so true or false so we'll take that xhr alright and actually you know what before we do that lets just console dot log the xhr all right just so you can see that this is actually an object with a bunch of properties and methods so if I click the button you'll see XML HTTP requests and it has all this stuff associated with it so it has an onload function which we're going to be dealing with it has a ready state with different values it has a status so HTTP status 200 is is normal you know 404 means it's not found so it has all these properties and methods assigned to it all right what we want to do here is we want to call open okay which actually it's not going to show right here but it has a function called open so we're gonna say xhr dot open and then like I said it takes in these three parameters first one is going to be the type of request which is going to be get then it's going to take the URL or the file name in our case it's just going to be sample dot txt and then it's going to be a true or false if it's going to be asynchronous or not so it's we're going to say true this is going to be a synchronous all right now there's two functions that we could use here one is onload one is onreadystatechange on ready state changes the older way of doing things and I'll kind of explain that in a little bit but first we're going to use onload all right and that's what we're gonna use throughout the series I keep saying series throughout the course so let's say onload XH our onload and we're gonna say equal function alright and then in here what we want to do is we want to check for the status of the response so we're gonna say if now we can say xhr dot status but since we're in this function we can actually just use the this keyword so we can say if this status is equal to 200 ok now 200 is is basically means okay when you make a request to a server 200 is okay and I'm just gonna paste in some comments down here so 200 is okay for outh 403 is forbidden 404 is not found what does this keep opening I don't want that open all right so we want to check to make sure it's okay before we do anything else all right now what I'm gonna do is just do a console dot log and we should be able to reget our to get our response from this file by saying this dot response text okay just like that so what we'll do is if we go ahead and we cloak we wrote we load this and we click get text file we're not going to see anything yet because there's one last function we need to call on that send so we're gonna go right below the onload still within the load text function and we're gonna say xhr dot send okay and I'll just put a comment here send request all right so let's go ahead and save and then we'll reload and click get text file and you'll see that it gives us a response now we're logging the response but even if we didn't do that so if I comment that out you'll see it's not gonna log anything but with the chrome tools if we go to network and we reload and you'll see there's nothing down here if I click the button all of a sudden you'll see this sample text you'll see it has a status of 200 it has a type of xhr and if we click on it you'll see all the headers I just want to make this a little bigger so the headers with the request type which was a get we have a 200 response it gives us all the the you know the content type which is text plain gives us the date all that stuff and then it gives us the response which is the content of that file all right so we're getting that data even if we're not doing anything with it from within onload we're still getting it in the browser all right so what I want to do now is show you the old way of doing things which was using onreadystatechange instead of onload okay so what I'm gonna do is just for now comment this out and then we're going to say xhr dot onreadystatechange equals function all right and then when we do this we do need to check for the status but we also need to check for something called the ready State all right now I'm gonna paste in something else in down here and this is just the different states that the request goes through so 0 is going to be requests not initialized one is server connection established two is request received prot 3 is processing requests and four is request is finished and response is ready so when we use onreadystatechange we actually have to make sure that we're at number four here okay so and here we need to do if this dot readystate which is a property of xhr and we want to we want to make sure that that's equal to four all right and then and we want to make sure that the status is equal to 200 okay and then we can do what we want we can console dot log same thing we can console log this dot response text all right so now if we go ahead and save this and go and reload and click you'll see it does the same thing that it did with onload all right now the difference with onload is this is not going to run unless ready state is ready unless it's at four so what I want to do is is go to some different points and show you what the ready state actually equals so we'll go right under where we did the right under where we did the open and we're gonna console dot log let say so we'll say ready state and let's say xhr dot ready state okay remember it's it's a property of xhr so if we go ahead and save that and we go ahead and click the button you know what let me get rid of the console log of the text just to clear that up all right so let's click it we get ready state one so at this point of the of the whole thing we're at 1 which is server connection established now let's go down to onreadystatechange and let's go before this check ok and we'll do the same thing we're gonna log the ready state before the check so if we go ahead and now you'll see it goes through one two three four okay so it's actually going through all of those until we check for and then we want to do what we need to but with onload it's not going to go through all of these checks so if I go ahead and I comment this out and we go and uncomment this and we go and we put our checkout readystate and save and click the button you'll see we get one right here and then here it's already at four okay so onload is not going to run unless it's ready that's the biggest difference between these two all right hopefully that makes sense now it's perfectly fine for you to use on ready state change instead of onload just know that you have to check for the ready state here as well all right and then we also have a method for on xhr called on progress alright so we'll say optional and let's say this is usually used for like loading or loaders you know and when you go to and you click something or you go to a page and you see the little round loading thing little gif image that's usually signifying that you're waiting for something so if you want to do something like that you can use on progress so xhr dot on progress equals function and let's go ahead and log the ready state here okay so we'll click that and you'll see that that's actually on three okay on progress is on three which is what processing request okay so if it hangs or something or if it's waiting in that progress state you're gonna see your your little loader there if that's what you how you set it up alright and this is completely optional I'm just trying to show you guys the different you know properties and methods attached to this xhr object now one more thing that you should do if you're going to use onload is you should also you also use on error in case something goes wrong you want to have that handler so what we'll do is go right under it and say xhr dot on error and just set that equal to function and then I mean you can handle it how you want I'm just gonna do console.log what and we'll just say request error all right now you're not gonna need all this stuff I'm you know like I said I'm just going through you're not gonna need both onreadystatechange and on load you're not going to need on progress unless you want it you want some kind of loader all right so it's not as hard as it looks right here and you're gonna see that in the other files that we create all right now you can do whatever you want with the return data in this case we were just console logging it but if we want to put it into the actual web page what we could do is let's just put in a couple line breaks and we'll create a div with the ID of text and then what we'll do is go right here and we'll say document dot get element by ID text and we'll say dot in our HTML equals this dot response text okay so if we go and we reload and click that brings the text right in okay and it does it all asynchronously there was no reloading of the page or anything like that it's all behind the scenes okay and this is a very very simple example of what Ajax can do obviously you can do a lot more this is just just to give you an example now you can test for other statuses as well so right now we're just testing for 200 which means everything's okay but we could also do like elsif and let's say else if this dot status equals 404 which is a not found then we could con sexually we don't have to console.log we'll just put it here in the in the text okay so we'll say document dot get element by ID enter HTML equals and we'll say not found all right and now if I go when I change this to sample to dot txt which we know there isn't a file called that but if I save and we go when we click we're gonna get not found it's also gonna tell us down here all right but just in case you want to handle that somehow like putting it in the actual page you can do that as well okay and there's a lot of different HTTP statuses if you want to go ahead and do a search the Mozilla website is really good for stuff like that alright guys so that's gonna do it for this file so that's basically just kind of explaining everything now we're just gonna jump in and we're gonna we're gonna make this a little more simple and you know leave out these comments and these explanations and stuff like that so let's create a new file let's see so we'll create a new file called Ajax two dot HTML all right and let's put in some basic HTML tags and we'll say Ajax - so this one we're gonna be fetching Jason or you know let's say local Jason and what I'm gonna do is create two files here one is gonna be user dot jason and then one is going to be users dot jason okay so for user dot jason i'm just gonna paste this in so very simple we just have an object here with an ID a name and an email we'll save that let's go to users and we're just gonna paste in adjacent array of users with an ID name and email and you may recognize these names here if you're cool alright so let's save those close them up and that's the data that we want to fetch so let's go to Ajax - dot HTML and then what I'll do is in the actual HTML on the body let's create a button with the ID of button one hand will say get user and then we'll have another button we'll call this button two and we'll say get users all right and then we just want I let's see what I want to do let's let's just put in a couple line breaks and then we'll have a div with the ID of user nothing in it just the div and actually it's putting each one above it Emmet is really kind of acting up lately so say user and then right below that will say users and change that to users so that's our HTML now let's put in our script tags okay and we want to document dot get element by D we want button one and we want an event listener so add event listener want to listen for a click and we want to call a function called load user all right let me turn on wordwrap can make this smaller too so now we're going to go and create that function load user all right and we're gonna kind of do the same thing that we did in the other file we're going to create a variable xhr we're gonna set it to new xml httprequest all right and then we want to call xhr dot open we're gonna make a get request and then the URL or the file name in this case it's going to be user dot jason and then true for async all right then what we want to do is is use our on load so xhr dot onload set that to function okay we want to check to make sure everything's ok with the status so if what we want to do an if so if this dot status equal to 200 then for now we'll just console dot log this dot response text all right and then of course we need our send so down here we need to say xhr dot senton now you should put in your on error here as well but i'm just gonna leave it out so let's save that let's go over here and reload let's say get user and there we go so it's getting the user from user dot jason now you may think if we go ahead and we put this in a variable like user and then we say console dot log and we say user dot name okay because you can see it clearly has a name value just make this smaller so if i save that we reload and we you click that you'll see we get undefined okay the reason for that is because we actually have to wrap this in a function called jason dot parse if we want to be able to access the probably the values that way so if we reload click it now we get rick okay so now we can get user dot email or user dot and so on so let's take this user and let's out put it into this div right here so we'll get rid of the console.log and we'll create a variable called output and we're gonna set that we're just going to initialize it with an empty value here and then we're gonna just append on to it so we're gonna say output output and then we can append with plus equals okay so we're gonna say plus equals let's put a ul and then if we want to go on to another line we have to put a plus now if this were a production prod project I would be using es6 temp template strings or template literals where we can use backticks and we don't have to concatenate like this but I want you guys just to have this and you know pure es5 JavaScript I know it's it's a little more difficult but you should know how to do it anyways alright so let's go ahead and continue this here so next line will be the Li will have an Li so let's go Li like that and then we want to concatenate in here well we'll say ID and then we'll concatenate in like this so user dot ID and then let's just copy that paste in two more so that'll be ID this will be the name this will be the email all right and then finally we'll just have an ending ul and we can end this with a semicolon so that's basically our HTML string or our output string and then what we can do is we can say document dot get element by D we want to grab the element with the ID of user so user dot inner HTML equals output so let's go ahead and save it let's go up here and reload click get user and there he is there's Rick so what we've done is we've fetched data from the JSON file behind the scenes asynchronously and we've built a template string or an output string and we've output it into the browser and this is this was all done asynchronously without having to reload the page or anything like that all right so if we wanted to get users which is an array that's gonna be pretty similar let's do that with this button too so what I'll do is add another event listener with button two and we're gonna call a function called get let you load users all right and then what I'll do is copy the entire load user function paste that down here change that to load users this time we want to get users Jason and let's see we're gonna go down here now since we're getting an array we need to do this a little differently we need to actually do a loop so that we can loop through and then append the output append the UL to each user so we're gonna wrap this in a for loop we're gonna say for I'm actually going to use a for in loop so we'll say var I in users which should be this okay that should be users and let's see we're just going to wrap let's see we want this to end right here oh okay so you don't want to have this this document.getelementbyid d you don't want that in the loop all we want to do is just add in the output in the loop all right and then we're gonna output this to users so let's put an S right there and save and then we can still get the single user if we click get users now the reason we're getting undefined for these is because since we did a loop here we actually we can't access it with just user dot ID we need to say users and then the current iteration so we need to put an I brackets and an I like that okay and then we'll save let's try it again get users and there we go so now we're getting them all all right so that's how we can fetch some local jason with ajax all right now what i want to do is i want to show you how we can work with an external API so we're going to use the github api which is extremely public extremely easy to use we don't need any authentication or anything unless we're making a ton of requests so let's create a new file called ajax three dot HTML and let's go ahead and put some structure in here we'll say ajax three handle six sternal api so in the body all i want to put here is a button will give it an idea of users i'm sorry an idea of button and let's say load github users okay we'll put a couple line breaks and we'll put an h1 I'll say github users and then we'll just put a div with the idea of users okay all right now for the github API all we have to do is visit an eight URL which is HTTP slash slash API github.com slash users and it'll give us a list of the first hundred users you could you could add parameters to filter this and stuff but we're not we're not gonna get into that I just want to show you how to actually make the request so that's the URL we're gonna make the request to instead of just a local file like we've been doing alright and like I said some servers are different some API is you need authentication they need cores enabled which which has to do with cross domains and you know using your client on a different domain than the server and it can get really complicated but what we're gonna do is go down here and put in our scripts and let's put a document dot get element by ID button and we want to add an event listener for a click and we want to call load users alright so let's go ahead and actually put a comment here we'll say load github users and function load users and what we want to do is grab our xhr object that and we're gonna call xhr dot open it's gonna be get now for the second parameter it's going to be this URL so the github API slash users and then just add true here all right then we'll do our onload okay so in here let's go ahead and check for status if this dot status is equal to 200 then we want to create a variable called users set it to jason dot parse and this dot response text okay so that should give us the actually let's just console.log the output here users all right we got we need to do our send so let's make sure we go down here and say xhr dot send and save and then let's go to ajax three dot HTML click load github users and there we go there's all of our users so i want to output these into the browser so what we'll do is kind of the same thing we've been doing let's create a variable called output and set it to nothing and then we're going to loop through so we're gonna do for for VAR users i'm sorry for VAR i in users and we'll say output plus equals and let's just depend a bunch of stuff here so we're gonna put in a div with the class of user alright and then let's see we're gonna put an image because if we look at what we can get here we can get an avatar URL which is the actual image of the the github user so in the source attribute here we're going to concatenate so single quotes and then plus sign and we'll say users i dot avatar underscore URL alright and I'm just going to give that a width of 70 and a height of 70 alright so that'll give us the image let's concatenate the next line so we'll put a UL here and then we'll do an Li and then inside the Li we're gonna put the login you see we have access to all this data we just want the actually let's do the ID and the login okay that's that's really all I'm going to use here so ID will have to concatenate users i dot login I'm sorry dot ID okay and we're going to copy that this one will be the login and then we'll have the closing ul and then we'll have the closing div all right and that should be our output string so now we want to go under the loop and just do document dot get element by ID we want the users ID and we want to say dot in our HTML equals output so let's save let's go back and reload and there we go so now we're fetching all those users putting them into the HTML now I'm just gonna add a very very simple styling up here so in the head let's put in some style tags and I'm gonna take the class of user and let's say display flex which will just align them horizontally and we'll give them a background of light gray and let's do a padding of 10 pixels and do a margin bottom of 10 pixels all right and then for the UL so I'll just say user and ul I just want to take away the bullets so we'll say let's type none all right so let's reload click it again and now it'll look like that so a little nicer and that's how we can use Ajax to fetch data from an external API asynchronously behind the scenes and and put it into our web page all right so the next thing we're going to do is we're gonna work a little bit with PHP so what I'm gonna do is create a new file here called process dot PHP all right now if you're not using xampp or some kind of server that has PHP installed this will not work so make sure that you're using either xampp or WAMP or you're on an actual Apache server maybe on a bun 2 machine or something like that all right so for now what I'm gonna do is just put in a PHP tag and I'm just gonna echo out a string that says processing okay we'll save that and then we're gonna create a new ajax file so we'll say ajax for dot HTML and close that up now a lot of you probably know how to submit a form to a PHP file okay so you can make a get request with the form or a post request so i'm gonna show you how to do that first and then how to submit a get request form and post request through Ajax alright so let's go ahead and put some markup in here and this is gonna be Ajax 4 and we'll just say ajax and pete PHP forms I don't know all right and then let's see in the body actually before we do the forms let's just put a button in just to show you we can fetch data from PHP so we'll say button let's give it an ID of button and it will say get name alright and then we'll put in our script tags and then let's do a event listener so document dot get element but get element by ID button add event listener we want to click and what we'll do is we'll call a function called get name okay let me just turn on word wrap I don't know why word wrap doesn't just stay on so let's create a function called get name and what we're gonna do here is we're going to set up our xhr object okay we're gonna say xhr dot open this is gonna be a get request to our PHP file which is process dot PHP and we'll say true alright and then we'll do our onload and let's just do console dot log and we'll log this dot response text okay we just need to do our send and let's save okay we'll go to Ajax four and if I open up the console here and I click get name you'll see we get processing so it's just getting whatever is in this PHP file now what I want to do is I want to send a get variable to process PHP now when you work with PHP and don't worry about it if you don't know PHP there's gonna be some stuff in these files you're not gonna really understand but what I want you to understand is just the way that Ajax interacts with PHP okay or just how Ajax works in general with with a couple different examples so what we can do is we can check for a get variable alright we can do that by saying if and then PHP has a function called is set and if you want to learn more about this kind of stuff with PHP I have a core course in on YouTube called PHP front to back where we go over all this stuff alright so we're gonna say if is set money sign underscore get which represents the get super global and we're going to search for a variable called name if that exists then we want to echo and we'll just say get your name is and then we're gonna concatenate on money sign underscore get name by the way this is this is pretty unsafe just you know outputting stuff like this but I just want to show you how it works there's actually security monk shion's you should wrap around these and stuff but I'm not going to get into that so let's save that now the way that we can send a variable to process PHP is by adding on to it and a question mark and we can say name equals and let's say name equals brad alright so we'll go ahead and save that and let's reload and we'll say get name and we get get your name is Brad so we sent this value to the PHP file and it's getting it with this and it's outputting it to us all right now this right now is hard-coded so what if we want to have a form that we can submit and we can we can get you know whatever the name we put inside the input so let's do that so I'm gonna create a couple forms up here let's go right below the button I'll just put in an HR and we'll say form first of all let's just do it through regular PHP so for that we would have we would say method equals get it is get by default but I like to put the method anyways and then the action which would be the actual file which would be processed dot PHP alright and then in here we'll have an input type of text and then it would have a name which would represent that that get name variable we're gonna set that to name alright and then we'll just put in a input submit and we'll say value equals submit alright so if we were to submit this form we'll just say John and submit it actually will you know make a normal request to process dot PHP it will redirect us it also put that name variable inside the URL since it's a get request all right now with Ajax what we want to do is we want to submit it behind the scenes and not actually have it redirect to the page so what we'll do is copy this you know what we'll do is put an h1 right here oops and let's say I'll just say get form so this is a normal PHP get form alright and then this one here is going to be an Ajax get form so we don't need any of this crap because they're not actually submitting it to the PHP file we're gonna do it through JavaScript so what we'll do is give it an ID of let's say get form we also want to give the input an ID so that we can access it so we'll give it an ID of name actually let's do name one all right and then what we'll do is go down here and let's do another event listener but at this time we're not going to do the button we're gonna listen on the form which does the idea of get form so let's say get form and then we're not listening for a click it's gonna be a submit of the form okay and then we're gonna call the same function get name which is this function here now when we submit a form by default it's gonna do what we just saw it's gonna try to go to a new file so what we need to do is pass in an event parameter here and then just stop that from happening with prevent default like that alright and then we can continue now we want to get the value of this input because that's what we want to use for this name okay so what we'll do is we'll say variable name equals document dot get element by ID okay it has an ID of name one except we want to get the value of it so we're gonna say dot value all right just like that and then what we'll do is replace this hard-coded Brad with name okay we're gonna need to concatenate it like that and then we'll get the response text so let's go ahead and save and let's reload so this is the regular get form if we submit it it'll get reloaded and you know make a normal HTTP request with the Ajax form if I say John and submit it'll do it behind the scenes we get it back and then we're just console logging it okay and we can of course do whatever we want with it we don't have to just log it we can bring it into the web page and we can do whatever we want with it all right let me put let me fix that title all right so hopefully that makes sense guys I know it's a little difficult to understand so now we're going to do is we're going to do the same thing but with post with a post requests okay when you use a post request when you're doing something like like adding data to a server when you're you know submitting to a server and you're saving data things like that it's much more secure so first we'll do the regular post form just like we did with the get so we'll go down here and we'll say post form we'll change the method to post okay it's still gonna go to process PHP let's save it and then in process PHP we can actually kind of do the same thing and we can check for for post variables so let's copy this so we'll check for post and we can use the post superglobal just to differentiate it let's go ahead and write post right here so we know what we're getting back and then post there okay so if we go when we reload and we say hello we submit it gets redirected you can see we get post your name is hello so it's just it's redirecting us to the actual PHP page and it's outputting that so now let's do the same thing with Ajax so what we'll do is we'll copy the ajak get form paste that end this is gonna now be the post form okay and then we're gonna change the ID to post form and change the ID of this to name two just to kind of to differentiate these two all right so let's copy this event listener sorry for moving kind of fast guys as if this video is getting really long so this is going to be a an event listener for the post forum and it's gonna call a function called post name alright so what we'll do is go down here and let's see I guess we could just copy get form cuz it's kind of similar and we'll change it to post form our post name sorry so the the form submits right we need to stop the you know the initial submit and then we're gonna grab the value of - name - which is this right here okay and then instead of making a get we're gonna make a post request now with post request we don't attach the parameter like this so we're gonna get rid of that and we just need to add what needs a quote there we need to add another property called set request header under open so we're gonna say xhr dot set request header and we need to set the content type okay since we're sending a post request so we're gonna say content - type and we want to set that as application I spell that right application slash X - WWE for my URL encoded okay that's that the content type that we want to send this as and then down here when we send it this is where we need to send our params so what I'm gonna do and what I mean by params is the is the name so we're gonna create another variable called params up here and we're gonna set it to name equals and then we're going to concatenate on the name variable which is this which comes from the form and then all we have to do is pass that in to send so it saved that and let's reload let's go to our Ajax post form we'll say Tom and submit and we get processing post your name is Tom alright so it looked at this right here and it gave us this back ok as our response and of course we could do whatever we want with that all right now I'm gonna take this a step further we're gonna get a little more complicated don't worry about it if you don't know everything that's going on in PHP but we're gonna actually submit the data when we make our post requests I want to submit it to the database to a MySQL database so I mean even if you want to stop the video here if it's getting too difficult that's fine but I do want to just keep going just to show you guys so in process dot PHP we're going to connect to a database all right you have to have MySQL installed if you have xampp installed then you do have my as mysql in fact you also have a tool called PHP myadmin so you could go to localhost / PHP myadmin and you can see your databases so we're gonna cook quickly create a database by clicking here database name I'll just call it test or actually let's call it ajax test all right now we're gonna create a table called users with two columns all right now we're gonna have an ID for the user which will be an integer and let's say 11 length and it's gonna be make this bigger it's going to be auto increment meaning it's going to the ID is going to increment by one every record that's passed in and then we want it to be the primary key and then we're just gonna have a name which will be a varchar' variable character and we'll say a hundred for its max all right and save so we have a database called Ajax test with a user's table with an ID and a name okay I remember that so now what we want to do is connect to our database we can do that by creating a variable called Conn or whatever you want to call it and we're gonna set my SQL i underscore connect and if you're interested in this kind of stuff again PHP front to back we go through all of this stuff so we'll say localhost is going to be the host we connect to my password for my databases root and I'm sorry the username and then my password is one through six and then the database we want to use is Ajax tests because that's what we just created all right so now what we want to do is go into where we check the post right and we want to create a variable here called name and we want to take the post name and we want to wrap it in a function called MySQL real escape string and this is really important for security so we're gonna say MySQL I did I say MySQL I meant MySQL ha i underscore real underscore escape underscore string all right so let's go ahead and paste in here the connection and then the post name variable okay so now this name is gonna equal whatever is passed into the input form all right and then what we want to do is go down here and say query we're gonna set it to an SQL query which will be insert into users remember we have a table called users and we just want to insert the name and then say values and the value is going to be that name value that's passed in from our form okay then what we need to do is check for the query so we're gonna say if MySQL I underscore query we need to pass in the connection and we need to pass in the query that we just created which is the insert query so if that happens and it goes in everything goes okay then let's just say echo user added okay else then something went wrong and we can just echo error and you can actually get the actual error string which will just whoops want to go like that we'll just concatenate with MySQL MySQL i underscore error and then that just takes in the connection all right and that's it so let's save it let's go back to our form and reload let's go to our post form cuz that's what we're working with and we'll say John we'll say John Doe and submit so it gets our post your name is your name is John which is coming from this line here I probably should have got rid of that and then we get user added because it went through all this and I and it looks like it actually worked so we can check it by going to our database going to our Ajax test database going to users and now there's John Doe okay so what we've done is we've made an ajax request through this form to our PHP file and then our PHP file actually inserted that into the database okay and we got back a request which is just this user added I'm sorry not a request a response so if we go when we add another name let's say I will just say Kevin looks like Kevin Hart and submit we get post your name is Kevin Hart a user added we should probably get rid of that line that's kind of confusing we'll save that alright we'll add another one we'll say Harry White submit processing user-added now let's check our database reload and we have those three names all right now one more thing I want to do is I'm going to create one more ajax file called ajax five dot HTML and what we're gonna do here is i want to fetch the users from here through ajax okay so what we're gonna do is create another PHP file and I'm gonna call this users dot PHP and just to save some time I'm gonna paste this in so we're connecting just like we did in the other file this should actually be a Jax test and then we're selecting all from the users table and we're getting the result and then we're gonna fetch the data put it into a variable and then we're gonna echo it out but we're gonna wrap it in jason and code and what this does is it'll take our result our associative array that's returned from the database and put it into JSON format okay and then give it give us a response so let's save that and then we'll go to our new Ajax five file and then this is actually going to be very similar to Ajax two where we just got it from users Jason so what I'm gonna do is copy that file paste it in let's go ahead and change this to let's say Ajax five and we'll say fetch from PHP MySQL and we only need one button so it's just so we'll say button ID one will say get users and then we're just gonna have the h1 with the users and then an ID of users okay then we want an event listener for just that one button and it's gonna call load users okay so we have two functions here load user and load users I'm going to get rid of the singular load user and we just

Original Description

In this video we will dive into AJAX with Vanilla JS and NO JQUERY. We will examine the XHR object and how it works. This is a beginner friendly tutorial for anyone that has very basic JavaScript knowledge. We will make xhr requests to a txt file, local json files, an external API and even PHP files. CODE: Files for this course http://www.traversymedia.com/downloads/ajaxcrash.zip BECOME A PATRON: Show support & get perks! http://www.patreon.com/traversymedia ONE TIME DONATIONS: http://www.paypal.me/traversymedia FOLLOW TRAVERSY MEDIA: http://www.facebook.com/traversymedia http://www.twitter.com/traversymedia http://www.instagram.com/traversymedia NEW DISCORD CHAT SERVER: https://discord.gg/traversymedia
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Traversy Media · Traversy Media · 0 of 60

← Previous Next →
1 Changing Your DNS/Nameservers
Changing Your DNS/Nameservers
Traversy Media
2 Create a MySQL database in cPanel
Create a MySQL database in cPanel
Traversy Media
3 Install & Uninstall Joomla Extensions
Install & Uninstall Joomla Extensions
Traversy Media
4 Adding and linking an article in Joomla
Adding and linking an article in Joomla
Traversy Media
5 Create a Joomla Blog
Create a Joomla Blog
Traversy Media
6 Import & Export A MySQL Database
Import & Export A MySQL Database
Traversy Media
7 Use A Custom Font On Your Website Using CSS
Use A Custom Font On Your Website Using CSS
Traversy Media
8 Connect Joomla Site With Dreamweaver
Connect Joomla Site With Dreamweaver
Traversy Media
9 Remove Phoca Gallery 3.2.3 Footer Text
Remove Phoca Gallery 3.2.3 Footer Text
Traversy Media
10 Drupal 7 Security Update 7.19 to 7.20
Drupal 7 Security Update 7.19 to 7.20
Traversy Media
11 Add An Addon Domain In Cpanel
Add An Addon Domain In Cpanel
Traversy Media
12 Pull A Heroku Rails App and Database
Pull A Heroku Rails App and Database
Traversy Media
13 Create a Custom Joomla 2.5 Module - Part 1
Create a Custom Joomla 2.5 Module - Part 1
Traversy Media
14 Create a Custom Joomla 2.5 Module - Part 2
Create a Custom Joomla 2.5 Module - Part 2
Traversy Media
15 Create a Custom Joomla 2.5 Module - Part 3
Create a Custom Joomla 2.5 Module - Part 3
Traversy Media
16 Joomla SEO Tutorial - sh404sef Configuration
Joomla SEO Tutorial - sh404sef Configuration
Traversy Media
17 Font Dragr
Font Dragr
Traversy Media
18 Convert an HTML Template to Joomla 2.5/3.0 - Part One
Convert an HTML Template to Joomla 2.5/3.0 - Part One
Traversy Media
19 Convert an HTML Template to Joomla 2.5/3.0 - Part Two
Convert an HTML Template to Joomla 2.5/3.0 - Part Two
Traversy Media
20 Rockettheme Rocketlauncher   Joomla Site in Under 10 Minutes
Rockettheme Rocketlauncher Joomla Site in Under 10 Minutes
Traversy Media
21 JQuery FAQ Slider Tutorial
JQuery FAQ Slider Tutorial
Traversy Media
22 301 Redirect With htaccess File
301 Redirect With htaccess File
Traversy Media
23 Convert HTML to Wordpress Theme - Part 1
Convert HTML to Wordpress Theme - Part 1
Traversy Media
24 Convert HTML to Wordpress Theme - Part 2
Convert HTML to Wordpress Theme - Part 2
Traversy Media
25 Easy JQuery Widgets
Easy JQuery Widgets
Traversy Media
26 Codeigniter App Part 1 - Creating the Database
Codeigniter App Part 1 - Creating the Database
Traversy Media
27 Codeigniter App Part 2 - Installation and Configuration
Codeigniter App Part 2 - Installation and Configuration
Traversy Media
28 Codeigniter App Part 6 - Login/Register System
Codeigniter App Part 6 - Login/Register System
Traversy Media
29 Codeigniter App Part 7 - Models List CRUD
Codeigniter App Part 7 - Models List CRUD
Traversy Media
30 Codeigniter App Part 8 - Models Task CRUD
Codeigniter App Part 8 - Models Task CRUD
Traversy Media
31 Node.js Part 1 - Install NodeJS on Windows
Node.js Part 1 - Install NodeJS on Windows
Traversy Media
32 Node.js Part 3 - Building a Static Page Server
Node.js Part 3 - Building a Static Page Server
Traversy Media
33 Node.js Part 4 - NPM
Node.js Part 4 - NPM
Traversy Media
34 Node.js Part 2 - Install MongoDB in Windows
Node.js Part 2 - Install MongoDB in Windows
Traversy Media
35 Create a Joomla Quickstart with Custom Sample Data
Create a Joomla Quickstart with Custom Sample Data
Traversy Media
36 Install MongoDB in Ubuntu
Install MongoDB in Ubuntu
Traversy Media
37 HTML5 Web Storage
HTML5 Web Storage
Traversy Media
38 Create a Joomla Bootstrap Template From Scratch
Create a Joomla Bootstrap Template From Scratch
Traversy Media
39 Ubuntu Server 14.04 Setup Part 1 - Installation
Ubuntu Server 14.04 Setup Part 1 - Installation
Traversy Media
40 Ubuntu Server 14.04 Setup Part 3 - Set Static IP
Ubuntu Server 14.04 Setup Part 3 - Set Static IP
Traversy Media
41 Create A Wordpress Widget - Part 1
Create A Wordpress Widget - Part 1
Traversy Media
42 Create A Wordpress Widget - Part 2
Create A Wordpress Widget - Part 2
Traversy Media
43 Create A Wordpress Widget - Part 3
Create A Wordpress Widget - Part 3
Traversy Media
44 Create A Wordpress Widget - Part 4
Create A Wordpress Widget - Part 4
Traversy Media
45 Get Started With Sass on Windows
Get Started With Sass on Windows
Traversy Media
46 Build An HTML5 Template With Bootstrap and SASS - Part 1
Build An HTML5 Template With Bootstrap and SASS - Part 1
Traversy Media
47 Build An HTML5 Template With Bootstrap and SASS - Part 6
Build An HTML5 Template With Bootstrap and SASS - Part 6
Traversy Media
48 Build An HTML5 Template With Bootstrap and SASS - Part 4
Build An HTML5 Template With Bootstrap and SASS - Part 4
Traversy Media
49 Build An HTML5 Template With Bootstrap and SASS - Part 5
Build An HTML5 Template With Bootstrap and SASS - Part 5
Traversy Media
50 Build An HTML5 Template With Bootstrap and SASS - Part 3
Build An HTML5 Template With Bootstrap and SASS - Part 3
Traversy Media
51 Build An HTML5 Template With Bootstrap and SASS - Part 2
Build An HTML5 Template With Bootstrap and SASS - Part 2
Traversy Media
52 Build An HTML5 Template With Bootstrap and SASS - Part 7
Build An HTML5 Template With Bootstrap and SASS - Part 7
Traversy Media
53 Build An HTML5 Template With Bootstrap and SASS - Part 10
Build An HTML5 Template With Bootstrap and SASS - Part 10
Traversy Media
54 Build An HTML5 Template With Bootstrap and SASS - Part 8
Build An HTML5 Template With Bootstrap and SASS - Part 8
Traversy Media
55 Build An HTML5 Template With Bootstrap and SASS - Part 11
Build An HTML5 Template With Bootstrap and SASS - Part 11
Traversy Media
56 Build An HTML5 Template With Bootstrap and SASS - Part 9
Build An HTML5 Template With Bootstrap and SASS - Part 9
Traversy Media
57 Build An Audio Player Using HTML5 & jQuery - Part 1
Build An Audio Player Using HTML5 & jQuery - Part 1
Traversy Media
58 Build An Audio Player Using HTML5 & jQuery - Part 2
Build An Audio Player Using HTML5 & jQuery - Part 2
Traversy Media
59 Youtube Data API v3 & jQuery To List Channel Videos
Youtube Data API v3 & jQuery To List Channel Videos
Traversy Media
60 Using Bootstrap With Ruby on Rails
Using Bootstrap With Ruby on Rails
Traversy Media

This video teaches the basics of AJAX using Vanilla JavaScript, including making requests to local files, external APIs, and PHP files, and handling responses. It covers topics such as JSON parsing, error handling, and security considerations.

Key Takeaways
  1. Create an AJAX request using the XML HTTP Request object
  2. Open a file and retrieve its contents using the AJAX request
  3. Check the status of the response and log it to the console
  4. Use the onload event to handle the response
  5. Parse JSON data from the response
  6. Handle errors and exceptions in AJAX requests
  7. Use PHP to process data and send it back to AJAX
  8. Use MySQL to store and retrieve data
💡 The xhr object is used to make AJAX requests, and the onload and onreadystatechange events are used to handle the responses. JSON data can be parsed from the responses using the JSON.parse() function.

Related Reads

Up next
Brisbane Catholic Education Frontier Transformation: Turning AI Ambition into Human Impact
Microsoft Cloud
Watch →