How to Create An Ajax-Based HTML5 Contact Form

Contact form is deadly essential for any website, as it acts as a messenger which passes the opinion or inquiries of visitors to the webmaster. There have been countless contact forms on the web but unfortunately, most of them do not explain to you the inner working parts, so here comes a detailed tutorial to teach you to build an advanced contact form from scratch based on the pop technology, HTML5 and CSS3.

Considering the nature of a web-based e-mail contact form we are also required to dive into two separate application fields, which is the PHP backend code for sending email and jQuery functions for rich user interface. By the end we will be left with a fully dynamic and functional contact form written with later customization in mind.

Get started now to build your own advanced contact form!

Shortcut to:

  • Download – Download all files (php + css)

Structuring the Application

To get started you’ll need some type of web server to work over. If you’re running a Windows machine WAMP is probably your best option. Mac users have a similar program named MAMP which is just as easy to install.

These packages will set up a local server on your machine with full access to PHP. Alternatively, if you own server space or have full server access into a remote location you may use that instead. We are not going to need any MySQL databases, which should simplify things a bit.

Once your server is set up create a new folder to house the application. You can name this whatever you’d like as it isn’t detrimental or even related to the final product. The folder structure will be used when you access your files in a web browser. A simple example would be http://localhost/ajaxcontact/contact.php

Let’s Build our Files!

We will only be working within 2 core files. We’ll first need a core .php file to house not only our application logic, but also frontend HTML markup. Below is sample code taken from our starting file.

<!DOCTYPE html>
<html xmlns:fb="" xml:lang="en" lang="en"> 
<title>HTML5/CSS Ajax Contact Form with jQuery</title>
<script type="text/javascript" src=""></script>
<link href="styles.css" rel="stylesheet" type="text/css" />

To begin we have written a simple heading section to our document. This includes a general Doctype declaration for HTML5 and some HTML/XML document elements. These aren’t exactly required, but will ease the rendering process in older (and newer) browsers. Also it never hurts to offer more information.

A bit further down we can see 2 lines right before our closing heading tag. The first includes our jQuery script from the online Google Code Repository. This is required for our dynamic page errors to work. Directly below this we have the inclusion of a basic CSS document containing all of our page styles.

Inside our document body we have a few containing divisions withholding a main contact form. This houses 3 input elements for the user’s name, e-mail address, and personal message. The HTML markup is fairly standard and shouldn’t boggle the mind of any intermediate developer.

<!-- @begin contact -->
<div id="contact" class="section">
	<div class="container content">
	 <?php if(isset($emailSent) && $emailSent == true) { ?>
     	<p class="info">Your email was sent. Huzzah!</p>
     <?php } else { ?>

Here we have a basic PHP conditional code nested within a few page containers. This checks for the set value of a variable named $emailSent and if equal to true, it will display a success message.

Inside our Form HTML

The else statement is what will run on first-page load since there won’t be any content to send initially. Inside here we will include a brief collection of form elements and a submit button.

<div id="contact-form">
	<?php if(isset($hasError) || isset($captchaError) ) { ?>
    	<p class="alert">Error submitting the form</p>
    <?php } ?>
	<form id="contact-us" action="contact.php" method="post">
		<div class="formblock">
		<label class="screen-reader-text">Name</label>
		<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />
		<?php if($nameError != '') { ?>
			<br /><span class="error"><?php echo $nameError;?></span> 
		<?php } ?>
		<div class="formblock">
		<label class="screen-reader-text">Email</label>
		<input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
		<?php if($emailError != '') { ?>
			<br /><span class="error"><?php echo $emailError;?></span>
		<?php } ?>
		<div class="formblock">
			<label class="screen-reader-text">Message</label>
			<textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
		<?php if($commentError != '') { ?>
			<br /><span class="error"><?php echo $commentError;?></span> 
		<?php } ?>
		<button name="submit" type="submit" class="subbutton">Send us Mail!</button>
		<input type="hidden" name="submitted" id="submitted" value="true" />
<?php } ?>
</div><!-- End #contact -->

You may have noticed there is another conditional block directly after the starting form. This checks for a variable named $hasError and will display an error message upon confirmation. This fallback method is only used if JavaScript is disabled in the browser and thus can’t generate dynamic errors.

All the way down we can find individual PHP variables being checked. The statements are regulating if the form has already been submitted with only partial amounts of data filled in. This is another fallback system which displays the contents of fields already filled out – a nice trick for proper user experience!

Directly after our form completion is the few jQuery functions we’ve written. We will talk over these first since they are the default implementation on pageload. However if the browser doesn’t accept JavaScript then by default we can rely on our PHP code.

Opening to jQuery

The easiest way to get started talking on this topic would be to dive right in. I’ll break down individual blocks line-by-line so you can see what the script is actually checking for.

However if you get lost just review the project code files. All of the full blocks are pre-written and well documented in the jQuery website. To get started we open our code similar to any other:

<script type="text/javascript">
$(document).ready(function() {
	$('form#contact-us').submit(function() {

The first few lines are checking for specific event occurrences. After our CDATA comments to hide the code from older, buggy browsers we get started checking for ready events.

The first bit checks if the document has fully loaded and is ready for manipulation. This is a classic technique and the easiest way to start coding a jQuery project.

Once inside we are checking for a form element under the ID “contact-us“, and we want to know when it is submitted. Upon doing so we call another function to display our error messages or slideUp() upon success.

$('form#contact-us .error').remove();
var hasError = false;
$('.requiredField').each(function() {
    if($.trim($(this).val()) == '') {
        var labelText = $(this).prev('label').text();
        $(this).parent().append('<span class="error">Your forgot to enter your '+labelText+'.</span>');
        hasError = true;
    } else if($(this).hasClass('email')) {
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        if(!emailReg.test($.trim($(this).val()))) {
            var labelText = $(this).prev('label').text();
            $(this).parent().append('<span class="error">Sorry! You\'ve entered an invalid '+labelText+'.</span>');
            hasError = true;

First we remove any pre-existing errors so we don’t hold any previous messages from before. A few lines down we can see a selector for all elements under the class “requiredField“. These are all of our required field elements – name, e-mail, and message.

jQuery will take the value of each field and remove all spaces from the value. If the content is equal to nothing, then we display an error message next to that field warning our user to fill in some value. Right before the end of our logic there is a bit of Regex code validating the e-mail value.

Lastly we can see if no error is set and check for full input content. If this is the case we call a jQuery method named post(). This will submit our form and check within the PHP code for any errors. Assuming none are found the slideUp() animation is called to hide our contact form and display a “success!” message.

if(!hasError) {
	var formInput = $(this).serialize();
	$.post($(this).attr('action'),formInput, function(data){
	$('form#contact-us').slideUp("fast", function() {				   
		$(this).before('<p class="tick"><strong>Thanks!</strong> Your email has been delivered. Huzzah!</p>');
	return false;	

If you are familiar with callbacks you may notice the post() function has a built-in set of parameters. Callbacks are smaller functions which are called upon the response of data from another function.

So for example, when our function successfully shoots an e-mail it will call its own internal function to display the sliding animation. All of this code could be written in its own block and moved elsewhere. However for the sake of this tutorial it’s much easier writing the callback as an inline function.

Breaking past our PHP

The final hurdle to mention is the logic behind our PHP processor. This is the backend system which will actually call a mail function and send out the message. All of the code used in the examples below can be found directly at the top of our main .php file, before any HTML output.

There are also a few internal styles which freshen up the page. There isn’t anything specifically new here so we won’t be going into any of the details. However the styles.css document is included within the project code and contains rudimentary CSS3 techniques.

//If the form is submitted
if(isset($_POST['submitted'])) {

To start we open our PHP clause and check if the form was even submitted. The POST variable “submitted” was actually a hidden input field added at the very end of our form. It’s a useful way to check if the user has submitted anything yet so we don’t waste server resources.

After this we have 3 separate if/else statement checking to see if each input field has been filled out. I won’t include each bit of logic here since they are all very repetitive in nature. However, to give you a brief example I’ve included the e-mail verification clause below:

// need valid email
if(trim($_POST['email']) === '')  {
	$emailError = 'Forgot to enter in your e-mail address.';
	$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
	$emailError = 'You entered an invalid email address.';
	$hasError = true;
} else {
	$email = trim($_POST['email']);

PHP will trim all whitespace from the value and check to see if anything is left over. If so we have a detailed Regular Expression (Regex) to see if our user’s input string matches up with an e-mail pattern.

You certainly don’t need to understand how preg_match() works to build this script. It is a useful function to determine rules and requirements for a successful type of data, but commands advanced programming knowledge to really grasp. In this scenario we are ensuring the user only inputs a select few characters, includes an @ symbol followed by 2-4 characters representing a Top-Level Domain.

After all of our logic passes and we return no errors it’s time to send our message! This bit of code will set individual variables to customize our e-mail message and setup some mail headers for the process.

// upon no failure errors let's email now!
	if(!isset($hasError)) {
		$emailTo = '';
		$subject = 'Submitted message from '.$name;
		$sendCopy = trim($_POST['sendCopy']);
		$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
		$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
        // set our boolean completion value to TRUE
		$emailSent = true;

If you were wondering how the code was going to figure out your e-mail address, this is the part to fill in. The first variable in our set is titled $emailTo and should contain whichever e-mail address, which is going to receive the message.

Inside our $body variable we take advantage of the \n delimiter to add new lines into the message. This adds small placements for the sender’s name, e-mail address, followed by a break for their message content. Of course you could spend time prettying up the display, but this structure works just fine.


This closes our tutorial for an advanced contact form. If you’d like to style your elements in relation to mine you can check out my example styles.css within the project code. However, the page is structured well enough that you could design your own look & feel very easily.

Feel free to download the source code and examine what I’ve done a bit closer. It’s good to follow a tutorial but having direct access to the project source can be invaluable. I’ve also included a brief stylesheet to make customizations a breeze, thanks for your view!