Site Beginner

Learn How to Build Websites

  • Make a Website
  • Start a Blog
  • BlueHost Review
  • About
  • Blog
  • Contact
You are here: Home / Code / Simple AJAX PHP Email Form with Validation

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.

Contents

  • What you need to get started
  • Creating the layout of the form
  • Writing the PHP email form script
  • Adding AJAX to a PHP email form
  • Bringing the contact form together
  • Download the free AJAX PHP email form

What you need to get started

Before you build this form, you'll need to have the following set up:

  1. A a web host that allows you to run PHP. I recommend some cheap hosting options here.
  2. A code editor to create the PHP, HTML and Javascript files. For this tutorial, I'm using Sublime 2.
  3. 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:

<form method="post" action="contact.php" name="contactform" id="contactform">

			<fieldset>

			<legend>Enter your details below to get in touch:</legend>

			<label for="name"><span class="required">*</span> Your Name</label>
			<input name="name" type="text" id="name" size="30" value="" />

			<br />
			<label for="email"><span class="required">*</span> Email</label>
			<input name="email" type="text" id="email" size="30" value="" />

			<br />
			<label for="phone"><span class="required">*</span> Phone</label>
			<input name="phone" type="text" id="phone" size="30" value="" />

			<br />
			<label for="subject">Subject</label>
			<select name="subject" id="subject" style="width: 302px;">
			  <option value="Feedback">Feedback</option>
			  <option value="Question">Question</option>
			  <option value="Contribute">Contribute</option>
			</select>

			<br />
			<label for="comments"><span class="required">*</span> Your comments</label>
			<textarea name="comments" cols="40" rows="3" id="comments"></textarea>

			<p><span class="required">*</span> Are you human?</p>

			<label for="verify">   3 + 7 =</label>
			<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />

			<input type="submit" class="submit" id="submit" value="Submit" />

			</fieldset>

			</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 <span class="required">*</span>.

There is also a drop down box for the Subject type using the <select> and <option> 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)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/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 '<div class="error_message">Whoops! You must enter your name.</div>';
	exit();
} else if(trim($email) == '') {
	echo '<div class="error_message">Oops! Please enter a valid email address.</div>';
	exit();
} else if(trim($phone) == '') {
	echo '<div class="error_message">Uh oh! Please enter a valid phone number.</div>';
	exit();
} else if(!is_numeric($phone)) {
	echo '<div class="error_message">Yikes! Phone number can only contain digits.</div>';
	exit();
} else if(!isEmail($email)) {
	echo '<div class="error_message">Sorry! You have enter an invalid e-mail address, try again.</div>';
	exit();
}

if(trim($subject) == '') {
	echo '<div class="error_message">Eek! Please enter a subject.</div>';
	exit();
} else if(trim($comments) == '') {
	echo '<div class="error_message">Oh no! Please enter your message.</div>';
	exit();
} else if(!isset($verify) || trim($verify) == '') {
	echo '<div class="error_message">Forgot something? Please enter the verification number.</div>';
	exit();
} else if(trim($verify) != '4') {
	echo '<div class="error_message">Shucks! The verification number you entered is incorrect.</div>';
	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 "<fieldset>";
	echo "<div id='success_page'>";
	echo "<h1>Thanks for getting in touch!</h1>";
	echo "<p>Thanks <strong>$name</strong>! Your message has been sent and we'll be in touch soon.<</p>";
	echo "</div>";
	echo "</fieldset>";

} else {

	echo 'Something went wrong!';

}

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('<img src="assets/ajax-loader.gif" class="loader" />')
			.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(){$(this).remove()});
				$('#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 <head> section of your web page:

<link href="style/contact.css" rel="stylesheet" type="text/css" /> <!-- Some simple styling for this form -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <!-- The latest version of JQuery so our contact.js works -->
<script type="text/javascript" src="js/contact.js"></script> <!-- Our JQuery code to send the information without reloading the 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:

[download id=”1085″]

Finally, make sure to backup any files or scripts before modifying them to avoid inadvertently crashing your website.

(Visited 9,612 times, 1 visits today)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

9 + 1 =

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!

GET STARTED

Popular Posts

  1. How to Start a Blog Using WordPress
  2. How to Point a Domain Name to Your Site
  3. How to Accept Credit Cards on Your Website
  4. An Ever Growing List Of Ways To Make Money Online…
  5. What is a Parked Domain & How Does It Work?
  6. The Best Domain Registrars To Use In 2023
  7. Choosing a Free HTML Editor to Build Your Website
  8. How to Pick Profitable Website Ideas
  9. What is a Domain Name and How Do They Work?
  10. What is Affiliate Marketing?

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!

GET STARTED

Categories

  • Apache
  • Building a Website
  • Code
  • Domains
  • General
  • Make Money Online
  • Reviews
    • Ecommerce
    • Website Builders
  • Web Hosting
  • Website Traffic
  • WordPress

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.

  • Best Blogging Platform
  • Best WordPress Hosting
  • Online Business Ideas
  • Shopify Review

Copyright © 2007-2023 All Rights Reserved.
Site Beginner · About · Create a Blog · Learn

Copyright © 2023 · SB2 on Genesis Framework · WordPress · Log in