- Simple AJAX PHP Email Form with Validation
- What you need to get started
- Creating the layout of the form
- Writing the PHP email form script
- Thanks for getting in touch!
- Adding AJAX to a PHP email form
- Bringing the contact form together
- Download the free AJAX PHP email form
- Leave a Reply Cancel reply
- How to Make a Website A complete guide for beginners.
- Popular Posts
- How to Start a Blog A complete guide for beginners.
- Categories
- Amazon Affiliate Disclosure
- FTC Disclosure
Simple AJAX PHP Email Form with Validation
When you design and build a website it’s very likely that you’re doing it because you want to be contacted by your visitors or to get feedback from them for something. This is why a PHP email form is such a popular request for first time webmasters.
This tutorial will walk you through creating a PHP email script which has both form validation and AJAX loading (which means the form will be submitted without the page being reloaded).
If you’d rather just grab the download link to get the source code, please click here.
What you need to get started
Before you build this form, you’ll need to have the following set up:
- A a web host that allows you to run PHP. I recommend some cheap hosting options here.
- A code editor to create the PHP, HTML and Javascript files. For this tutorial, I’m using Sublime 2.
- An FTP client to upload the completed script files to your web server. I’m using FileZilla.
Once you’ve got all of this ready we can start to create this PHP form script.
Creating the layout of the form
The first step is to build the HTML layout of the form and include all of the information we want to capture through the form. The kind of things you might want the user to input include:
- Their name
- Their email address
- Their phone number
- The subject/reason for enquiry
- Their message
For this form we’re going to include all of those items, but you are free to add or remove inputs from the form depending on your needs. Here is the basic markup for this form:
Notice that we have action=»contact.php» at the beginning of the form. This is the script we’ll write that the form will post the user inputs to so we can email the details.
Each label and input has been named appropriately and we have specified required fields using * .
There is also a drop down box for the Subject type using the and HTML elements which you can change on your own contact form to whatever subjects you’d like.
Finally, there is a simple verification question to prevent spam bots from being able to submit to your form. It’s basic, but you can enhance this and make it stronger as you learn more PHP.
Once you’ve got your basic form markup, you’ll need to save it as index.html so we can come back to it a little later to finish off.
Writing the PHP email form script
Now we have the form, we need to be able to take the information submitted by the user and do something with it (i.e. email it to an address of your choosing.
We also need some error handling in case the visitor forgets to enter one of the values in the form, and we also need to check they have entered a valid email address as well.
For the email address, we can do a check to make sure they are using a valid domain name extension as well as only alphanumeric characters (letters a-z and numbers 0-9). To do that we can use preg_match which can search the entered email address to check it matches our criteria:
function isEmail($email) < return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|((75?|115|[2]13|[2][5]4)\.)(39?|191|[2]23|[2][5]3))$/i",$email)); >
Next, we can check to see whether or not our contact form submission has all of the information we need from the visitor, and if not we can display an error message on the page to let them know what they did wrong:
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n"); $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $subject = $_POST['subject']; $comments = $_POST['comments']; $verify = $_POST['verify']; if(trim($name) == '') < echo ''; exit(); > else if(trim($email) == '') < echo ''; exit(); > else if(trim($phone) == '') < echo ''; exit(); > else if(!is_numeric($phone)) < echo ''; exit(); > else if(!isEmail($email)) < echo ''; exit(); > if(trim($subject) == '') < echo ''; exit(); > else if(trim($comments) == '') < echo ''; exit(); > else if(!isset($verify) || trim($verify) == '') < echo ''; exit(); > else if(trim($verify) != '4') < echo ''; exit(); >Now that we have some error-handling sorted out, the next step is to decide where we want to email this contact form, and what we want to put in that message. We’ll put these in as options that you can change if you want to, but with default values.
OPTION 1: The email address to send the feedback form to
// OPTION 1: Where do you want to send the completed contact form? // Enter the email address that you want forms to be sent to. // Example $address = "john.smith@example.com"; $address = "john.smith@example.com";Just change john.smith@example.com to the email address you want to receive the forms to.
OPTION 2: The subject line for your contact form email
// OPTION 2: What do you want the subject line of your contact form to say? // The standard subject will appear as, "[New Feedback] You have an enquiry from John Smith." $e_subject = '[New Feedback] You have an enquiry from ' . $name . '.';By default, this will say [New Feedback] You have an enquiry from John Smith. but you can change this if you’d like to.
OPTION 3: The body content of your contact form email
$e_subject = '[New Feedback] You have an enquiry from ' . $name . '.'; // OPTION 3: What do you want your contact form email to actually say? // Modify the body of the email here. // If you want to add more fields to the form - add them here too. $e_body = "You have been contacted by $name with a message for $subject. Here is their message:" . PHP_EOL . PHP_EOL; $e_content = "\"$comments\"" . PHP_EOL . PHP_EOL; $e_reply = "You can contact $name by email at $email or call them at $phone";This is how the email message will appear in your inbox. By default it will appear as:
You have been contacted by John Smith with a message for Questions. Here is their message:
“This is where the message will be displayed.”
You can contact John Smith by email at john.smith@example.com or call them at 0123456789.
The final part of this script is to put the entire email message together and if it is successfully sent, display a confirmation message on the page:
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 ); $headers = «From: $email» . PHP_EOL; $headers .= «Reply-To: $email» . PHP_EOL; $headers .= «MIME-Version: 1.0» . PHP_EOL; $headers .= «Content-type: text/plain; charset=utf-8» . PHP_EOL; $headers .= «Content-Transfer-Encoding: quoted-printable» . PHP_EOL; if(mail($address, $e_subject, $msg, $headers)) < // Email has sent successfully, so let the user know. echo "
«; > else
And that’s it! Your PHP email form is complete and will send the information to the email address of your choosing. The last step is to use some Javascript/JQuery to make this happen seamlessly, without the page loading.
Adding AJAX to a PHP email form
Ajax is a way of sending and receiving information to a web page without changing or reloading that page. So when you post a status update to Facebook, for example, it gets added automatically without the page and all the images etc being loaded again.
To do this with our feedback form, we need to use a small JQuery script:
jQuery(document).ready(function()< $('#contactform').submit(function()< var action = $(this).attr('action'); $("#message").slideUp(750,function() < $('#message').hide(); $('#submit') .after(' ') .attr('disabled','disabled'); $.post(action, < name: $('#name').val(), email: $('#email').val(), phone: $('#phone').val(), subject: $('#subject').val(), comments: $('#comments').val(), verify: $('#verify').val() >, function(data)< document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#contactform img.loader').fadeOut('slow',function()); $('#submit').removeAttr('disabled'); if(data.match('success') != null) $('#contactform').slideUp('slow'); > ); >); return false; >); >);This code adds a simple loading animation and submits the information via email without reloading the page. Once the information has been sent, it will use a slide animation to display the success message. We’ll save this as contact.js so we can use it in our form.
Bringing the contact form together
At this point, your form should be fully functional as a PHP email contact form, but we need to make some final adjustments to our index.html file to make it work as expected.
We need to add the JQuery script we just saved, and also the latest version of JQuery itself, so our script will run. Also, we can add a stylesheet to make the contact form look more presentable. To do this, we can add the following code to the section of your web page:
Download the free AJAX PHP email form
If you’d rather not go through this tutorial to build your own PHP feedback form, you can download the demo instead and experiment for yourself. Remember: You’ll need to run it on a server running PHP for the code to work.
You can download the demo here:
Finally, make sure to backup any files or scripts before modifying them to avoid inadvertently crashing your website.
Leave a Reply Cancel reply
How to Make a Website
A complete guide for beginners.Want to learn how to make a website like this? Check out our beginner’s course now. It’s completely free!
Popular Posts
How to Start a Blog
A complete guide for beginners.Want to learn how to make a blog? Check out our beginner’s course now. It’s completely free!
Categories
Amazon Affiliate Disclosure
Sitebeginner.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com. Find out more here.
FTC Disclosure
I may receive customer referral fees from companies mentioned on this website, this does not affect the price you pay for any products you decide to buy. All data & opinions on this website are based on my experience as a paying customer.