Build an AJAX Contact Form in PHP That Sends Emails

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys today we'll be creating this contact form in php where communication is done asynchronously which means that we could actually send an email without a page refresh but currently these errors will appear because we haven't actually filled out these fields and as you can see when we did press send these errors displayed well to page refresh so we'll just enter in some dummy content here and we'll change this so we can get a new error now where this isn't a valid email format which is meant to be the recipient's email as you can see we're getting that error now and just to show you that this actually does work because we will be setting up an smtp server for free using gmail so that we can actually send emails we'll paste in the temp mail there and then we'll press send and again notice that is send and we get notified with this success message but the page never refreshed during that entire process and just to show that the email has actually been sent we can go back and just in time it actually does appear as you can see the subject dummy subjects the ball of the body is the same as the subject so if this interests you then keep watching [Music] so here we are in a new empty project folder because we are using php we will need to be running an apache server to host our files locally i have mine via xampp but you can set up yours manually if you want either way it doesn't matter as long as you do have one running and because i'm using xampp the project is located in the htdocs folder which is xampp's default web folder and inside my project folder i will launch up a terminal and then inside i will use the terminal to launch up vs code which is my source code editor of choice but obviously you can use whatever source code editor that you want we will start off by creating the index.php file it will be served to the client as soon as they try to access the home page route therefore we will use it to hold all of our markup content and inside we'll use the emit abbeviation to create the html boilerplate code i'll zoom in so that you can see that a lot better and we will give this a title and we will create a header so that we can display something other than a blank screen and before we check to see what this looks like we will create the style sheet for this page and we will create it in its own folder so that we can separate things out of it we will call it styles.css and the first thing that we would do is we would just configure some default stylings the box sizing border box will include elements and margin and padding in their final width and height values and we use asterisk selector to select all elements and then we will remove all of the margin and padding from all of the elements and then set the font family and now that we've created this we will just link to that style sheet like so but obviously it's in the css folder so i need to link to it like that css style it's actually styles.css and then now we will go to our browser and then we'll try it out local i think it was called ajax email so we'll need to go to that because that was what the project folder's called as you can see it's in the correct font so we know things are working so we'll go back to our vs code now and we will now begin creating the contact form and we will create it using the bm or block element modifier design pattern i won't be explaining it in this tutorial but i will post the link in the description for you to learn about it if you don't already know but essentially it is just a set of naming roles for css classes and we'll move to action because we don't need it and we'll also say well also turn off also complete because i just find it annoying to be honest so so none of the inputs will have suggestions but obviously that's that's your choice whether you want this to be enabled or not and the first thing that we will do is we'll create a label and it will be for an input of name it will say two and now we'll create the input and it will be a text input so we'll create it like that as i said before i would name a two and then we'll use bem to give it a class and that will be the name of the block which is email form but the name of the actual element itself is text and this use of double underscores is the standard syntax for bm again i won't be explaining bm in this tutorial but rest assured that this is the proper naming convention for elements it's the name of the block followed by two underscores and then the name of the actual element that we want to target and then we'll create another label and then another text input and again that will have a name that corresponds to the label and we don't want to give it an id we'll just give it a class like so it's name will be subject oh wait sorry yeah it's like type text your name you don't want to change that create one more label that'll be for message add it like so and instead of a input this will actually be a text area and it's class we want to give it its own unique class that'll be email form and it'll be a different element so i'm just going to call it text area its name will still be message and we'll finish this off actually with a button and that's a button i'll type submit again using emmett abbiation here and again that will be its own element so say email form submit and the text inside will just say send okay now i'll move on to styling this stuff so because it's not a real website we can just set the body to redisplay flex normally i wouldn't do that normally i'd have some kind of container class but the only thing it's not a complex ui the only thing that's actually on this web page will just be the header and the contact form so you can afford to get away with that so height it will be 100 viewing height but it can't be any smaller than 500 pixels and this will simply prevent the contact form from going outside the top edge of the document and we will send to everything on both axis so justify content and align items both recenter flex direction every column so elements will go from top to bottom not horizontally and then the title which is what we gave the header i believe yep again we'll just give it some margin on the bottom to counteract the fact that we removed or every element's margin in the asterisk selector which is the first selector that we created and then the email form which is remember the block that was the actual form elements which contain the two inputs and the text area we'll give it 10 pixels vertical padding 20 pixels horizontal padding give it a very thin black border [Music] give it some margin so that it's 100 width but it can't get any larger than 500 pixels so on screen sizes where that are smaller than 500 pixels it will be 100 the width except not really because we have padding uh on both horizontal sides so it'll be a bit away from the edge of the viewport and we just want to check this out actually because i just realized i haven't actually viewed it so yeah a problem that i have here is that because inputs and other form elements are display inline by default it's been displayed horizontally here but we want them to be displayed in a column so vertically and the way that we will do that is we will simply target every direct child at the email form like so and then we will set the display to be block and it also gives some vertical padding as well and so now ufesh as you can see is displayed vertically now so that's how we get that effect we will now target the input of the form the two inputs because remember we had two inputs and one text area so this is for the two inputs but as for the text area email form and the name of the actual element so text area 100 the width of the container give it padding 10 pixels all around height i have a fixed height 220 pixels and what's that resize to be none it's like the user can't drag the size the text area around so now if you look see what this looks like as you can see it's looking good we will now begin to create the classes for the message elements they aren't actually hard coded into the markdown file because they will only be displayed on a relevant scenario like an error being met or the email being sent successfully but you saw a demonstration um at the start of the video what those messages look like it's like the error messages this particular class will be applied to the message that appears at the top of the contact form and it isn't related to a specific input and again you still had to start with the green success message we will then create some modifier classes for this class [Music] and in bm the naming convention for modifiers is elements class followed by two fight hyphens followed by the name of the modifier so in this case the name of the actual modifier is uh and it will be applied to this element class so it will have a lot of red because this will be the error messages for that for this message at the very top of the contact form and the other one will be it will be the success message so it will have color of green next we will create the class that will be applied to the error messages that are related to a specific input and these messages will contain things like this input cannot be left empty etc and we won't create any modifications for these they will all be error messages which is why it's just a set color of red as for the button we want that to have some padding so i'll give it some padding we also want it to be centered horizontally in the middle of the contact form something that we could achieve with margin auto for both horizontal sides thanks to us making or direct children of the contact form display block earlier on which is what we did up there and so now again we refresh well the button will be styled but the messages obviously they won't make any difference because the messages will actually be rendered onto the contact form they're not there by default finally we will decrease variation in browsers by manually writing out our own styling for these form elements [Music] now browsers set their own styling for form elements and this styling can vary between browsers so by manually defining our own styling we are overwriting the browser's default ones so font size 100 and family will be inherit so i don't know if you can see the form has actually changed slightly and it now it will now look consistent across all browsers we now want to create the frontend scripting for index.php file so that we can make the initial post request to our server so at the bottom of the body so is that the last thing to be loaded we will link to a script and it will be in its own scripts holder [Music] and it will be called emo for email form.js and we'll create that in the scripts folder as specified and then email form dot js like so and inside the first thing that we want to do is we want to create a reference to our contact form so that we could do something when the user submits it and we could use the query selector to do this because we only had one instance of this email form class in our dom so we could just target it like so and i need to show you another so we press if we just go to the root and we press send as you can see you get directed to this weird url route and the page obviously refresh refreshes to send us there and we don't want this because we're sending an asynchronous request we don't want the page to uh refresh because that will just defeat the whole purpose of having of sending asynchronous requests where the page doesn't refresh it's the way that we will prevent the page from refreshing on form submit is we will configure the unsubmit event handler for the form and it has access to the events through this through its argument which we've just called a and inside we could cut inside we could write code that'll be triggered when this form gets submitted and the first thing that we will do inside is we will prevent the page from refreshing using the event argument combined with the its prevent default method and this will do it exactly as described by a comment so we would just press send it's iv refresh uh as you could see press send now and the page is no longer um the page is no longer sending us anywhere which is good it's just staying where it is and after this we will create references to the free inputs on the contact form so we'll say email from a query selector to query all of the chart elements uh off the email form and the first input had a name of two so we'll just target it like that because remember they had all they are all the same classes so we will target it individually using an attribute selector and then we'll do similar thing here but i believe its name was subject that was the second input and then as for the message input that wasn't an input that was a text area so we'll say text area and there wasn't any other text areas so just writing out text area would suffice but anyway we'll be a bit more specific and we will include the attributes and value well then move on to actually creating a poster post and we'll do that using fetch api because it's gotten to a point now where it's supported widely enough for us to be able to use it obviously you don't have to use it you can use the traditional uh ajax object or you can use jquery if you want again you can find out how to do that on your own it's not really an ajax tutorial it's more of a php tutorial really how to create contact forms and send emails in php and it's very important that on the second argument of this fetch request that we include this headers content type field and we need to set its values to application json very important because we are sending json data to our server if we didn't include this content type header then you won't be able to do that and also it's absolutely essential because we're using apache server that we include this mode and credentials field because they allow us to send a request that is to be handled by the same local server that sent the request in the first place that's the body the data that will be held on this post request with json.stringify because again we are sending json data and we will have three fields that will represent the free field the free input of our contact form so to [Music] subject subject input.value got value because you want to send over the values of these inputs not the actual input elements themselves [Music] again we'll do it for the third one and then after that we will need to write to them method so when the server when you get response on the server service response data will need to be passed from json into javascript so that we can work with it in javascript and then once that's finished passing we will simply console.log res just for testing purposes so that we know that the server is can respond to our request and because we are sending a request to send email form.php in the libraries folder we need to create first of all the libraries folder and then inside we need to create that php file verbatim so make sure that it's named uh exactly how it was written here and inside we're only going to contain php code so we could just write the opening php tag like so and we don't need to write a closing tag so the purpose of this file is to handle the client's poster quest and respond to it by sending the email if there are no errors the first thing that we would do is make sure that this file is being requested in the correct way and we want to make sure that it is being requested from a post request that has the correct headers set before you begin to an email sending logic and to do this we'll get access to the value of the content type header that we created in the second argument of the fetch method and i don't know if you remember but it was called content type so we get access to it in this server super global and supervent and error we will use attorney operator and we will first make sure that the value does exist we're using the inset method which is built into php if it does exist then we'll get access to it with the trim method and the trim method will just use um it will remove unnecessary white space so it will just simply streamline our code but if it doesn't exist then we will simply assign content type to be an empty string to prevent any null errors and this if condition will be met if the content type is what we set it to be on the second argument of the fetch method so inside this if condition will be safe to create the email sending logic inside of here and the first thing that we will do inside is get access to the data containing the body of the client's post request we do that with this file get contents method and specify that we want the input data remember this should be adjacent object with three fields two for the two inputs and one for the text area again we will use the trim method for this it is very useful for removing discrepancies and our input data now our php can't actually work with json objects so to handle input data we will need to convert it into a format that is native to php and we can do that with this json underscore decode method the first argument is the json object that we want to pass and the second configures the pass json data to be a php associative array not a php object which is what this true billion does and this if condition will be met if the passing process was successful for now the only thing that we'll do inside is we will use this exit method to stop the script immediately as soon as this if condition is met because you want to see it the server can successfully respond to the initial post request or not before you do anything else now the exit method allows us to stop the script of exiting and return a value the value that we return must be passed into json with this json encode method if it wasn't then the client wouldn't be able to receive this data from the server and for now we will simply send back the decoded associative array passed back into json so the client should essentially get back whatever they submitted to the form in the first place and if we go back to the form remember we're locking it so we should be able to now we'll just uh refresh this just for luck so we just had some data here you know whatever press send obviously nothing should happen at the moment but we should if we go to console.log we should actually see that the data is formatted here so we know that things are working so we can go back to our php file so now that we know the server can respond properly we don't need this exit method anymore since it was only for testing purposes instead we want to loop through the associative array each item in the associative array which there should be three in this case we'll have the key represented by this name iterator and the value represented by value inside we will simply override the value of the item that is currently being looped through with the previous value passed into this filter method uh filter var method which i'll create now as you can see its second argument will be set to be configured um to remove any characters uh from this input data that is not suitable for the string format and we will wrap the output of this method in a trim method so that we can be dead certain that every value in this array is properly formatted ready for error checking which is what we do later on so we'll close it off with semicolon the first check that we will make is if the to field on the associative array holds an empty value if it does then we will need to somehow render an error message above the two input on the contact form informing the user that they need to fill out this input and to do that we will create this associative array in global scope all of its field correlates to different messages that can be rendered out on the contact form they are initialized to empty strings because they will only hold values if we need to show a message to the user like an error message for example as you can see you should be able to know where we're getting these names from or at least some of them because they they are the names of the input originally close it off like so if you don't get an hour and we initialized it in global scope so we can render out an error message to the user if the parent if condition wasn't met for any reason so outside of this parent if condition we will simply initialize the top error field of this array global associative array and we will write out a message [Music] like so and as soon as we initialize this top field we will return this array to the user remember it needs to be encoded into json as for this scenario we will initialize the two uh field instead [Music] and the error the message will need to be relevant the actual error condition and we won't immediately return the response here because there are still more errors to check for like for example this to do is not empty then there's still a chance that it is not formatted properly for an email and we'll be able to know that if we use this filter of our method and we say filter validate so we're not sanitizing here we are validating so this method will return false if it's not in the correct format for an email in which case we will need to create a new message that relates to this specific specific error message so we'll say it must be a valid email instead of empty as for the other two error messages they are a lot simpler for them we would only phone error the user has failed to input any data for them and in this case these conditions will even be met the user has inputted multiple white spaces in them because of the trim method that we used in the above for each loop actually we'll just copy this because it's the same message but just assigns a different field and we'll do the same for the other one as well the message let's copy the string from here though now if the user gets to this point in the if condition where they have passed all of the error checks then we want to begin sending the email [Music] however if they get to this point and one of the one or more the above error checks are met then we want to stop the script here and now because we only want to send an email if the user has passed through every single check without an error we can do that by looping through the response associative array like how he looped through the associative array above and if any of the value if um if any of the values in this array i'm not an empty string then we will stop the script and return the response immediately so that any code below will not be executed so we'll say exit if that condition is met on any of the values contained inside this associative array in order to return the response like we always do now if we get to this point here then we'll actually need to send the email and to do that you'll need two things an smtp server and a mail function in php so as for the actual smtp server you'll need to go to your google account just type in google account go to it here and then once you've signed in you'll need to go to i believe security and then you'll need to enable two-step verification i've already enabled it here and then what you'll need to do once you've been able to start verification you'll need to go to app passwords and then obviously you need to sign into your account i'll just jump cut to when i've done that okay once you've entered in your password you'll need to go to select app you choose custom and then you type in whatever you want i'll just type in test one to fix i've already generated my password as you can see but all you need once you've generated it you'll need to copy this make sure it's very important that you keep a record of this because once you press done you won't be able to see it again but then you press done but i'll delete it personally because i'm not i'm not going to be using that i'm going to be using one that i've already created so once you've created that and you've stored it haven't deleted it and you've noted down the password that it gave you you will need to go to php mailer and then you go to the github which should be the first link depending on what search engine you use click on download this and then you download it into your project folder or whether really because it's just a zip and inside your project folder you will need to rename this just for ease so you name it just a php mailer and then you just drag it into your boot or whatever you want really just as long as it's in your project folder you can delete the zip now and now that we've got that that's good actually let's go back to documentation because there's some to impose information that we can copy from her such as if we scroll down this all these uh imports are required in order for you to use a php mailer inside this document so copy it like here but we will change some of this you see when we're currently in the libraries folder because we'll need to go to the root directory where php mail is actually contained in but other than that we can keep the rest the same and what we'll now need to do is we'll now need to initialize php mailer and to do that we'll go to the php mailer documentation scroll down to this section and we will instantiate it in a variable called mail we'll do that here actually and we don't actually need the b in there and then we'll just copy some of this but not all of it we need to copy all of it stuff that i've highlighted or delete this just because comments aren't really important it kind of interferes with the word wrapping that we've got here and as for these values obviously these are just dummy content the actual values for our smtp server will need to be filled out in this ht access file so that we can declare some apache environment variables which is how we will be storing our smtp information because since it is private we don't want others to be able to view it the way that we do that we do with set e and v capital s capital e and every single uh one will need to we'll need to begin http and instead of space as well underscores and everything we need to be in capitals so this one will say php main host now by default no matter what your password was if you're using google's server it will be smtp.gmail.com and then we'll declare another one again the same if you're using the service it will be 5x7 and that's a number which is the reason why we didn't include quotations and then username again this will just be your email address your actual google email address and then as for the password that would need to be the password that you copied or that you should have copied anyway if not then you need to repeat the step of setting up a smtp server password i need to blow this out because this is actually a sensitive information and i definitely don't want other people to be using that but once that we've got that we actually need to create a dot get ignore uh just spot that right there you go file set this htaccess file can be ignored if we do decide to push this project to a git deposit tree so inside we'll just say ignore that file and if we didn't do this then others will be able to view this htaccess file from our git repository and that would simply defeat the whole point of environment variables of having them in the first place and with all this created i actually need to use these environment variables so that what they they'll be contained inside of the server cpu globals actually will go back and we will copy all of these copy them like so again i'll remove these because it doesn't matter you don't need them and actually i'll just cut to having all of these filled out so hold on a second there is a actually another thing that i forgot to include and that's the port it's very important because remember it was 587 so we'll include it here inside that whoops it needs to be on all caps for starters but we'll just include that now like so and actually all of this will need to be surrounded in a try catch block just in case there is an error in initializing php mailer we'll need to catch that exception and inside the catch block we will actually copy this and paste it in here so the user we can just send back a header error message to the user to be displayed on the contact form if there was an error initializing uh php mailer and one thing actually we start apache server just to make sure that these environment variables should be working uh properly but anyway we will now scroll down to remember where we were before below this for each loop and this is we'll get to the point now where we actually do send the email [Music] so we'll do that in a try catch block so the set firm this will be who the email is from and that can just be your email address that you used to create the smtp email address because it wouldn't really make sense to use anything other than that subject again well we'll get that from decoded like so and then we'll say mail is html this is kind of an option and we'll set that so yeah we are using html you'll see why in just a second because the body which is what the messages contents will actually be it will be in a paragraph uh whoops so it will close off like that and we use four stops to concatenate everything together and decoded we'll say message we'll go inside will be sandwiched in between those two paragraphs and then after that we will say add address and this will be the recipient of the email and the recipient obviously again we'll get that from decoded and then finally we'll say mail dot send and it should be pretty self-explanatory what the send method actually does then again we need to catch this if there was an error then we would do what we always do because that was a problem okay well this ad address uh oh yeah because it needs double d there you go solve that error and then if it gets this point where the catch block obviously wasn't met because if it was met then the exit method would be met and the script would just terminate we'll say the sex success response so you can mark what we're actually doing and inside the response we'll say success message has been sent like so at a full stop and then finally what do we always do send up send back json uh encode response and we should actually be done um with our php uh send email form file when i'll go back to our javascript file and we'll get rid of this console.log because we don't actually need it anymore or actually no we could keep it to be fair because it's not going to do us any harm it's good for testing purposes i guess and obviously i'll move it on a finished application but this is not a finished application so if the response is holding data on its 2r field then we will need to render out whatever it is holding on that field as an error associated with the 2 input on the contact form and the way that we do that is we will use insert a json.html method and the before given method which will mean that the html content of this methods second argument will be inserted directly before the opening tag of the element that this method is being used on and in this case that is the two input element and what will you actually use backticks because you want to use string concatenation here as you can see you're ending out a paragraph and the paragraph being displayed will uh while the page has been rendered will display whatever string is held in this 2r field so we will say 2r like so and we'll need to give it the relevant class so we'll say class email form msg remember we created that a while back but we will need to give it that class and we need to do the other ones as well so what we'll say we'll just copy them just for verity and what is the name again subject i think we leave it as yeah subject uh so we'll just change that change both of them at the same time you can do that by holding down alt in vs code change it like that and um yes this will need to be changed as well so we'll say we'll change it to subject input and then one more and this one needs to be message uh oh no i didn't highlight the second one this time oh well message uh and this this one is the message input and it will also need to have a different class and that will be email form actually that won't need to have a different class so that will be as it is but we what we will do is we'll say we'll do the one from the top uh and if this top uh field holds a value then the html content will be inserted as the very first child of the email form and this will be um sorry insert adjacent html and this will be configured with after begin like so so not before begin this time and inside again we use backticks like so and inside will render out top error and it will have a different class this time the actual class that it will hold will be email form top msg and it will need to be red so we'll copy that and it will use the red modifier so remember if you remember then it will double high funds and then error like so and after this this we will render out the success message but we can't do that if there are any other error messages that exist so if any of these ever messages do hold a value then we will simply return out of this callback function immediately so that the success message never has a chance to be of being outputted so we'll simply say return i'm going to use my mapping here and then finally again we'll just copy this just for ease we'll actually render out the top success and that will be again that'll be after begin and instead that will be obviously this will be top success and then this will be instead of uh it will need to be [Music] success well i had to sub your code on there just because uniformity and in addition to that we will also reset the form so that it's free inputs will be wiped clean of values and this will simulate the effects of a page refresh about actually refreshing the page and we'll do that with the other white also collected because that's a valid method as you'll see with the reset method like so so we'll actually try this out so we'll go to our application but we'll refresh so if we press send now as you can see we're getting errors so if we fill out this information now as you can see we get we have a problem here and the problem is we are not wiping these error messages on a new form submit so the way that we'll do that is we will create a function record and move our messages from form whoops and what we'll do we'll target the whatever form is passed into the method and then we'll use the query selector or method and we'll target every single element that contains msg in its class name or any of its class names that has multiple class name and because we're using for each it will return an array and we'll look for every single one of these elements that match the criteria and we'll simply remove it from the dom and this will work because all these messages they have msg as you can see hyphen msg hyphen msg uh yeah they've all got that they've all meet that criteria so all these will be removed on a new form submit and obviously we'll need to call this so this will actually be the first thing that will be called and we'll pass an email form so that actually works and so now if we refresh i know we get an error but we type a certification here we should get a different error must be valid email address so we'll get a valid email address so we'll go to whoops temp mail i don't write sorry temp mail we'll just go to this one quickly get one again copy that paste it in here okay that's now valid email and we'll just say dummy one two three abc and then hopefully success message has been sent everything's cleared let's see if it actually is working we refresh here and hopefully if we wait a bit we should actually get a yep so i was a bit hesitant then for a second but as you can see we are actually getting a message and yeah everything's looking good obviously you know i mean this looks good to me um if you have any queries or if my explanations were lacking in some areas then please don't hesitate to post your queries down in the comments box below i would be happy to hear back from you and i will answer all of your questions to the best of my ability and i'd also appreciate if you like and subscribe because i put in quite a lot of effort into making these tutorials and you'll be doing me a huge favor if you did that but more importantly have a great day and peace out guys
Info
Channel: Qixotl LFC
Views: 299
Rating: 4.7142859 out of 5
Keywords: How to send an email in PHP with AJAX, How to send an email in PHP without a page refresh, PHP contact form without page refresh, PHP contact form validation on the backend, PHP form validation tutorial on backend, PHP AJAX tutorial with fetch API, How to create free SMTP email server with PHP, How to send a real email with PHP and PHPMailer, How to send an email in PHP without page refresh, PHP AJAX email form tutorial with fetch API, Build a contact form in PHP using AJAX, AJAX
Id: 9pethq-xarE
Channel Id: undefined
Length: 47min 22sec (2842 seconds)
Published: Sun Jul 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.