Overview and Goals
Okay, so in this video what we're going to be doing is we're going to be submitting an HTML form with Ajax. So we're going to be using the jQuery Ajax library to submit this obviously without refreshing the page. But what we're also going to be doing is we're going to be careful as to create this so it's entirely flexible so that you can quickly implement it elsewhere. You don't have to build the same functionality for each form you use on a website. We also need to bear in mind accessibility. What happens if the user has JavaScript disabled? In that case we want to submit the form anyway. So we're going to build a form as we would normally submit it, but then we're going to let Ajax or our Ajax functionality handle the submission for users that can, and obviously we're going to keep our form semantics and everything like that. So this is how the form looks at the moment. Let's just go ahead and fill some details in here. So let's go ahead and pop our my name in, my email address, and a quick message. I'm going to go ahead and hit send. Now that has sent this data to a PHP file without us actually seeing anything and you can see here I've logged to the console what we've got back and that's just a print_r in PHP. So you can see at the moment we've got an array of data which is the name, email and message. This is actually printing out the POST global variable. So this is what we're going to be doing in the video. We'll start from scratch, build up the form and then build up our JavaScript functionality.
Okay, so basically what we're going to be doing is we're going to be building the form first that will submit to a specific page and that's going to be the page that we're going to process the data in. We're going to be building it as if we didn't have JavaScript enabled and we're going to ensure that it works first of all and then when that's done we can handle the rest with Ajax. This functionality, as I said, you can use over as many forms as you like and it's super quick to implement once you've done it. So the first thing that we want to do is build the form. Now let me just explain the elements that we've already got on the page. We've obviously got our basic markup on the page, we've got a title, now we've included jQuery, the latest version of jQuery from the Google CDN, and we've also included a file called main.js which is found here. Nothing in at the moment but that's where we're going to be writing our JavaScript, nothing too complicated. So let's go ahead and start to build out our form and give it the usual attributes that we would. So the action is going to be the page that we're submitting to. Now in this case I've created a folder called ajax and I've created contact.php which you can see I've got open in my editor. So that's the file that we're going to Ajax to. So I'm just going to choose ajax/contact.php and I'm also going to choose a method which is going to be post. The reason we do this is because we're going to use JavaScript to pick up the value of this attribute, but also if we submit the form it will go to this page to process the data inside of the form. So it falls back to people that either don't have JavaScript enabled or, you know, something might go wrong. So let's go ahead and create some input fields. We're going to have name, email, message and then the submit button. Oops. So the type here is text and we'll give this a name. Now the name is important. We're not going to give these any classes or IDs unless we of course use labels. In this case this is going to be picked up by JavaScript as well, so it's extremely important. I'm also going to incorporate a placeholder in here and just say 'your name'. So let's duplicate this down and we'll change this to email and change this to email. Let's again duplicate this down and we'll create our submit button while we're down here. Now we don't need a name for the submit button and we also don't need a placeholder. We just need a value for this so I'll just say 'send'. And obviously in here we want to go ahead and create a textarea. So we're basically building a form as we would, so there's nothing different about what I'm doing. This is going to be 'message'. So let's go ahead and check this out and refresh. So we've got your name, email, message and send. We'll go ahead and just wrap some divs around this. In fact we'll give this a placeholder too. Obviously this is going to depend on your design but I'm just going to wrap empty divs around this. You know, not recommended but just to space it out for now. I'm not going to apply any styles or anything like that and I'm certainly not going to use paragraph tags. Once that has done, let's just preview this. Cool, so we've got all the markup out of the way. Now we're going to get into the exciting stuff which is the PHP side of stuff which is going to be very basic because this isn't a tutorial about processing a contact form, but we'll then work on the JavaScript which is going to get a little bit more interesting.
Basic PHP Receiver and Fallback Behavior
So when I submit this to contact.php let's just take a look what happens. I'm going to fill out some details, send. Okay, so this has gone to ajax/contact.php. Inside of contact.php we want to create a conditional statement and we want to check if the data that we are expecting is set: POST name, POST email, POST message. Now obviously I'm using PHP but you could be using any server side language here. It does not matter where you're submitting this to as long as you can process this on the back end. So here I'm going to print_r our POST. We're not actually going to do anything with this data but you can do everything with this data. So when I go ahead and hit refresh you'll see that we've got an array of the data that I've submitted. So that is the point of this. Now what we want to do is actually take over this functionality. Click send, nothing's available. We want to take over this functionality and when we hit send we want to send this behind the scenes and then get that data back so we can either put it onto this form, redirect with JavaScript, something like that. So let's go ahead and write the JavaScript for this. Now it's not as complicated as you might think it is, actually extremely easy, and hopefully the way I explain it is going to clarify each step that we take. The first thing to do is to set a selector for our form. Now we don't want to just target every form. We want to target forms that we specifically want to enable Ajax for, so I'm going to give this a class of 'ajax' and that will mean that any form with a class of 'ajax' will be processed by this functionality. So I'm going to say form.ajax and I'm going to use the on method and I'm going to say on submit. So when this form has been submitted, a submit button has been clicked, the last thing I want to do is return false and the reason for this is otherwise the form will submit in its normal fashion. So when I click send, now nothing happens. Okay, so the event handler has been triggered. So we can do a console.log here to check. But there we go. We're not actually submitting the form in the traditional fashion.
So now what we want to do is we want to create some variables. We want to create a reference to the current object which is the form or the element, and we want to get the URL, the method, and we want to set some preliminary variables to hold the data that's going to be in this form. The beauty of this method is that if we want to go back to here and add another field we don't need to write any more code in the JavaScript area. This will all handle it. We're going to loop through all of the elements in here that we want to submit so you don't need to go and change everything. This will remain like you could implement what I'm about to write and never have to change it. So that's the beauty of this. I'm going to create a variable called that and this is going to reference the current object that we're working with. I'm also then going to say url equals that.attribute action and we also need to get the method so I'm going to say method equals that.attribute method and we also want a data variable which is going to be a JavaScript object to hold our data. Now if you don't really understand this, that references the current object that we're in, so that would be this form, so now we can use that to say that. It's just a shorthand way instead of using this and this over and over again. attribute is basically just one of the form attributes, that's action and method. So we grab them. Let's go over to the index.html file. So we grab the method and the action and we save them. Now what we want to do is we want to loop through all of the elements in the form. Which elements are we interested in? Well, we're only interested in elements that have a name because they're the ones that we want to pick up on the other side. The name is required for the traditional submission, but we want to pick up the value from these based on the name. So name, name, name. This doesn't have a name because it's not of interest to us. We could give it a name and it wouldn't matter, but anything with a name within the form is of interest to us. We say that.find and in here we choose another selector and the selector is literally just '[name]'. This means find anything with an attribute of name regardless of whether it's empty and regardless of what content is within it. Now we use the each method and we have a callback function so this will run for every single element with name and we'd expect that there would be three in this case. Let's console.log and let's put some value index value and in here let's say console.log value. When I click send you see that it basically outputs the three input fields that we're interested in: the name, the email and the message. Now that we've got that clear we need to create some more variables and again I'm going to create a that variable to reference this. Remember this now references each of the inputs that we've just seen output. So we're going to have a name for it which is that.attribute name and that reference is this, and we're going to have a value which is going to be that.val().
Build Data Object, Send via $.ajax, and Handle Response
Okay, so now we've got the values of each of the elements that we're interested in. We can append them to this data object here. The reason that we're appending to a data object is because we're going to be sending this through the Ajax jQuery method and we need to pass this as a JSON object or just an object. So we say data[name] equals value. This basically just says data[name] — the name of the input field — and then we apply the value. Under here I'm going to say console.log data. Let's go ahead and refresh. I'm going to type in Alex, my email address and 'hello' and click send. You see now we've got an object: name Alex, email [email protected], message hello. This is in perfect form to send through to our PHP file using the jQuery Ajax method. So we've built this up perfect. Now we can send it along. What we're going to do here is we're going to use the ajax method, some curly braces inside, and here we want to specify the url, the type of request which can either be get or post which we picked up here, and then we want to send the data through which we already have seen in action. So the url is just going to be the variable url, the type is going to be method — in fact let's change this to type and change this to type for consistency — and the data is data. This is sending the URL that we specified with this data, the type of request and the data is all of these values that we've already seen output. We also have a success callback function and in here we get a response and then we can console.log response. The Ajax method sends the data to this URL with this type, and then we get a response back which is basically anything that's output on this page which at the moment is print_r POST. So we'll just console.log the response. With this data you can do absolutely anything: you can clear the form, you can output error messages and get creative with that. Now let's go ahead and say Alex, Alex@phpacademy and 'hello' and click send and the response is the print_r of this. This isn't JavaScript; this is the print_r value of what we've seen in our contact.php. So we could even say 'your name is name' — so when I say Alex, I'm not going to bother filling these out. We don't actually have any checks to say these should be submitted, but there we go: 'your name is Alex.' We can do anything we want inside of our PHP file. We can pass error codes back and things like that and then we can pick that up within this callback here. Basically what we've done is we've created a form that can be traditionally submitted but we then overtake it with a JavaScript functionality, and then we have that nice fallback if it's not available and then we can process it in the back end with any server side language of our choice.