Create an AJAX/jQuery/PHP Contact Form

This tutorial uses XHTML, CSS, jQuery and a little PHP to make a pop-up/modal contact form that validates whatever is entered into the form and then uses AJAX to send the form without refreshing the page. Sounds complicated…actually it’s very simple!!

The code of this tutorial has been updated

The HTML Markup

The HTML layout of the contact form is very simple. You have your ‘normal’ webpage, whatever that may be. Somewhere within your website you’ll have a link with a class of modal.

The contact form requires two specific divs. Firstly a div with an id of #contact; and secondly an empty div with an id #mask.

All of the contact form, the alert boxes, the close link etc. go inside the #contact div. The form layout is simple: two text inputs, one textarea and one submit button (we’ll come back to this in the PHP section). These can be preloaded with values such as “Your name” which can be cleared for the user by setting the Javascript functions onFocus or onClick.

The #mask div must be empty. Although an empty div is not recommended practise, it’s a technique which works will for modal windows.

The modal window markup is based on this blog post from queness.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>TutToaster AJAX Contact Form</title>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<link rel="stylesheet" href="css/reset.css" type="text/css" />
<link rel="stylesheet" href="css/master.css" type="text/css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="contact.js"></script>

</head>

<body>

<div id="container">

<h1>This is a web page</h1>

<p>This is the main body.</p>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in lacus vitae tortor vehicula cursus a pretium odio. Suspendisse potenti. Phasellus semper nisl a massa vulputate at vulputate justo tempor. Quisque vel enim aliquam risus varius aliquam iaculis non odio. Pellentesque molestie, lorem vitae vestibulum porta, elit eros fringilla nunc, cursus ultricies nisi neque sed ipsum. Nam enim nisl, gravida sed consequat non, faucibus eget massa. Nullam pulvinar, diam et eleifend viverra, purus sem pellentesque sem, non tempor ante neque eu dolor. Quisque adipiscing, tortor ac feugiat feugiat, enim mi porttitor nunc, in bibendum diam sem eu leo. Morbi gravida, leo ut auctor cursus, urna nulla viverra eros, vitae dictum arcu quam sed odio. Proin eleifend urna a justo suscipit vehicula. Pellentesque vitae elit eros. Nulla vehicula velit nec dui vulputate viverra. Curabitur non dolor ac velit semper faucibus vel eget dolor.</p>

<p>A <a class="modal" href="#">contact link</a>.</p>

</div><!--end container-->

<!--contact form-->

<div id="contact">
	<div id="close">Close</div>

	<div id="contact_header">Contact</div>
	<p class="success">Thanks! Your message has been sent.</p>

  <form action="send.php" method="post" name="contactForm" id="contactForm">
  <p><input name="name" id="name" type="text" size="30" value="Your Name" /></p>
  <p><input name="email" id="email" type="text" size="30" value="Your Email Address" /></p>
  <p><textarea name="comment" id="comment" rows="5" cols="40">Enter your comment or query...</textarea></p>
  <p><input type="submit" id="submit" name="submit" value="Send" /></p>
 </form>
</div>

<div id="mask"></div>

<!--end contact form-->

</body>
</html>

The CSS

The CSS can be whatever you want. For this tutorial we’ve used some simple icons and some clean, white and grey colours. I recommend using a CSS reset file (a good example is Eric Meyers’ CSS reset, which can be easily edited for your personal requirements).

The most important aspect of the css file is that #mask, #contact, .success and .error need to have their display set to display:none. This makes sure that these div’s don’t show up when the page is loaded.

The width and height of the #mask div are set to 100% so that, when displayed, it fills the whole screen. It has a z-index of 9000 to make sure that it appears on top of most of the page, but below the #contact div, which has a z-index of 9999.

body {
color:#222;
font-size:16px;
font-family:helvetica, verdana, arial, san-serif;
line-height:1.5em;
}

a {
color:#06F;
text-decoration:underline;
}

p {
padding:10px 0;
}

#container {
width:900px;
margin:20px auto;
}

/*contact form*/
#mask {
background-color:#000;
display:none;
height:100%;
left:0;
position:absolute;
top:0;
width:100%;
z-index:9000;
}

#contact {
background-color:#fff;
display:none;
left:50%;
margin-left:-300px;
position:absolute;
top:90px;
width:600px;
z-index:9999;
border-radius:10px;
-moz-border-radius:10px;
-webkit-border-radius:10px;
padding:20px;
}

#close {
background:url(../images/close.png) no-repeat right;
cursor:pointer;
font-family:arial, sans-serif;
font-size:20px;
font-weight:700;
line-height:24px;
text-decoration:underline;
text-align:right;
padding:5px 30px 5px 5px;
}

#contact_header {
background:url(../images/envelope.png) no-repeat left;
font-family:arial, sans-serif;
font-size:30px;
font-weight:700;
line-height:50px;
padding:5px 5px 10px 60px;
}

/* form components */
input,textarea {
border:1px solid silver;
background-color:#fff;
color:#404040;
font-size:10px;
font-family:Verdana, Arial, sans-serif;
text-transform:uppercase;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
margin:10px 0;
padding:10px;
}

input:hover[type=text],input:focus[type=text],textarea:hover,textarea:focus {
background-color:#E0E0E0;
border:1px solid #000;
}

input[type=text],textarea {
width:300px;
}

#submit {
border:none;
width:87px;
height:41px;
background-image:url(../images/submit.png);
}

#submit:hover {
cursor:pointer;
}

/* alert messages */
.success,.error {
color:#000;
display:none;
font-size:15px;
font-weight:700;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
padding:5px 10px 5px 10px;
margin-bottom: 10px;
}

.success {
background-color:#9F6;
border:1px solid #0F0;
}

.error {
background-color:#F66;
border:1px solid red;
}

The jQuery

In order to use jQuery, you need to link to the source file. You can either download it from www.jquery.com and save it locally; or, to save time and bandwidth, you can use the version stored by Google. Also, to make this tutorial a little more tidy, the JavaScript is stored in a seperate file (called “js/contact.js”). You can see the link to this file (and jQuery) at the top of the HTML page.

The contact form will use jQuery to do two things: firstly it will validate the form and return an error if the data is not valid. Secondly, the AJAX capabilities of jQuery will be used to send the form data to a PHP file which will send an email and then return a success message. (To make the markup a little clearer, I’ve saved the jQuery function in a separate file: js/contact.js.) The Javascript file has three functions:

The first thing the jQuery file does is ‘listen’ until the link with a class of .modal is clicked. When this happens, the page scolls to the top of the page, and fades in the #mask div and displays the #contact div. Lastly, it returns false, to stop the default action of the link form occurring. (As a safety feature you could set the href of the link to direct to an independent contact.php page so that if Javascript is disabled the link will work like normal.)

The second function simply checks if the #close div is clicked. If it is, then the #contact and #mask divs are removed from the display. An option extra is also to set the same function to happen if the #mask div is clicked – so that the user can get rid of the modal window as easily as possible.

The third function is the biggie. When the #submit button is pressed it kicks in sets up some variables (the data submitted in the form) and runs a series of if/else checks. Firstly it check is the ‘name’ variable is not empty. Secondly it check if the ‘comment’ variable is not empty. Thirdly, it checks whatever is submitted in the email variable against a simple regular expression (see below). If the email variable passes the check, then the script uses jQuery’s AJAX function ($.ajax).

If any of these tests fail, the else statement kicks in and slides down an appropriate error message (which are simple divs included in the html markup but set to display:none by the css).

The AJAX function of jQuery is brilliant because it saves a whole lot of work. Instead of manually check what browser is being used, and setting up a HTTP.request and all that, all that needs to be done is to set five things: the type of data, the url which will handle the data, the data which is being sent, a function to run if successful and a function to run if unsuccessful.

In this contact form, the type is “post” and the url is “send.php” (see below). The data uses the variables name, email and comment which were set earlier in the sciript. The error and success functions are very similar and display either a success or error message above the form. The success function also hides the form, just for fun. (When the #close div is clicked the form is ‘unhidden’ ready for the next time its needed).

Additional note: the regular expression is quite simple. The forward slashes (/…/) indicate the start and end of the expression. Within those are three sections (marked by [...] brackets: any uppercase or lowercase letters, numerals, periods, underscores or hyphens [A-Za-z0-9._-]. Then it makes sure there is an @ sign. Then any combination of letters or numbers [A-Za-z0-9._-] followed by a . then a string of lowercase letters between three and five characters, including a period. This allows for email domains such as .com, .co.uk, .org.uk etc.

$(function() {

	// load the modal window
	$('a.modal').click(function(){

		// scroll to top
		$('html, body').animate({scrollTop:0}, 'fast');

		// before showing the modal window, reset the form incase of previous use.
		$('.success, .error').hide();
		$('form#contactForm').show();

		// Reset all the default values in the form fields
		$('#name').val('Your name');
		$('#email').val('Your email address');
		$('#comment').val('Enter your comment or query...');

		//show the mask and contact divs
		$('#mask').show().fadeTo('', 0.7);
		$('div#contact').fadeIn();

		// stop the modal link from doing its default action
		return false;
	});

	// close the modal window is close div or mask div are clicked.
	$('div#close, div#mask').click(function() {
		$('div#contact, div#mask').stop().fadeOut('slow');

	});

	$('#contactForm input').focus(function() {
		$(this).val(' ');
	});

	// when the Submit button is clicked...
	$('input#submit').click(function() {
		//Inputed Strings
		var username = $('#name').val(),
			email = $('#email').val(),
			comment = $('#comment').val();

		//Error Count
		var error_count;

		//Regex Strings
		var username_regex = /^[a-z0-9_-]{3,16}$/,
			email_regex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

			//Test Username
			if(!username_regex.test(name)) {
				$('#contact_header').after('<p class=error>Invalid username entered!</p>');
				error_count += 1;
			}

			//Test Email
			if(!email_regex.test(email)) {
				$('#contact_header').after('<p class=error>Invalid email entered!</p>');
				error_count += 1;
			}

			//Blank Comment?
			if(comment == '') {
				$('#contact_header').after('<p class=error>No Comment was entered!</p>');
				error_count += 1;
			}

			//No Errors?
			if(error_count === 0) {
				$.ajax({
					type: "post",
					url: "send.php",
					data: "name=" + name + "&email=" + email + "&comment=" + comment,
					error: function() {
						$('.error').hide();
						$('#sendError').slideDown('slow');
					},
					success: function () {
						$('.error').hide();
						$('.success').slideDown('slow');
						$('form#contactForm').fadeOut('slow');
					}
				});
			}

			else {
                $('.error').show();
            }

		return false;
	});

});

The PHP

The last part of the contact form is a simple php file. The PHP captures all the data that was send (via POST) from the Javascript file and stores them in some variables. Some further variables necessary for emails are set (subject, headers etc.). Finally it uses the PHP mail function to send the email.

<?php

//Prefedined Variables
$to = "web@yourmail.com";
$subject = "Contact from your website.";

if($_POST) {
	// Collect POST data from form
	$name = stripslashes($_POST['name']);
	$email = stripslashes($_POST['email']);
	$comment = stripslashes($_POST['comment']);

	// Define email variables
	$message = date('d/m/Y')."\n" . $name . " (" . $email . ") sent the following comment:\n" . $comment;
	$headers = 'From: '.$email.'\r\n\'Reply-To: ' . $email . '\r\n\'X-Mailer: PHP/' . phpversion();

	//Validate
	$header_injections = preg_match("(\r|\n)(to:|from:|cc:|bcc:)", $comment);

	if( ! empty($name) && ! empty($email) && ! empty($comment) && ! $header_injections ) {
		if( mail($to, $subject, $message, $headers) ) {
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}
}
?>

Conclusion

So, there you have it. A couple of divs, some simply CSS, the brilliance of jQuery and the shortest PHP file ever, and you can have a cool modal contact form!

Your free to use this form on all of your projects without any restrictions. You can freely use it for both your personal and commercial projects, only thing we would appreciate is a link back to this item when your using it. Icons by c9d and Oxygen

Themify WordPress Themes

This entry was posted on Friday, April 30th, 2010 at 10:38 am and is filed under Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Simon Patterson is a freelance web designer and developer based in South Wales, UK who loves to fuse beauty and function. Follow Simon on Twitter or visit his Blog

About the author Published by Simon

31 Responses »

  1. Poor usability, no client and server side validation… but design is great :-)

  2. Thanks g23,

    We will look in to this and will update the code asap ;)

  3. Its a beginner tutorial therefore validation could be ignored but resetting the textfields after onFocus (User typed text in it already) is a usability issue! :)

  4. Thanks for the tutorial. Perhaps, rather than

    $('input#submit').click(function() {

    you could use

    $('#contactForm').submit(function() {

    which would handle using the keyboard to submit the form?

  5. Yes, huge usability and validation problems. Say hello to spammers.

  6. Might want to check the PHP too, handling emails is a hard task and was poorly done here. I can inject headers into your code with your poor security.

  7. The code of this tutorial has been updated, thanks to Cody. Re-download the source files please.

  8. Good article.

    I have a suggestion when you receive data, that is using stripslashes is not always right. It’s right only when magic quote is enabled (by default, but some host disables it). You need to check it.

    And for validation, you can simply use strip_tags for removing all HTML tags to make sure user doesn’t submit harmful code.

  9. I agree with david above.
    The form process should be executed on form submit rather than on the click of the submit button.

    This is because it will skip all the lovely ajax if the form is submitted with the ‘enter’ button.

  10. hi,
    It nice web design tips, coding is ok but validation is not done..
    keep going on..

  11. Excellent tutorial thanks for sharing…

  12. @Ruchi

    You need to look closer, I added validation on the client side.

  13. it messes up my design …

  14. It seems that the form is not working properly. I have tested it on my site and the live demo and I get the same “invalid username” result. Please respond asap.

  15. Very basic. You can improve this tutorial by adding extra security like CAPTCHA and kicking server side validation automatically when JS is disabled. I’ve not checked the code in all the browsers but looks good.

  16. Here is a good one,
    Ajax’d Form with Fancy Email
    http://bit.ly/arltdj

  17. If your going to post a tutorial like this, don’t you think testing it would be a good idea? I also get “invalid username” result.

Trackbacks

  1. Web Mee Beta3
  2. Contact form building useful resources « Design Define's Blog
  3. Contact form building useful resources « Design Define's Blog
  4. Contact form building useful resources « Design Define's Blog
  5. Create an AJAX/jQuery/PHP Contact Form | RefreshTheNet
  6. Weekly Design News – Resources, Tutorials and Freebies (N.35) - Speckyboy Design Magazine
  7. Weekly Design News – Resources, Tutorials and Freebies (N.35) | crazyegg.net
  8. Comment créer un formulaire de contact gratuit en PHP/Ajax/Jquery (Tutorial)
  9. Weekly Design News – Resources, Tutorials and Freebies (N.35) | Master
  10. Enhance Forms Using jQuery: 30 Tutorials and Plugins
  11. Enhance Forms Using jQuery: 30 Tutorials and Plugins | Web Channel

Leave a Response

We do love friendly, well-constructed and respective comments. We do not love bitchy, stupid and disrespectful comments. Find something wrong in this post?, feel free to send us a note and we will fix the issue asap.

About tuttoaster.com

TutToaster

Tuttoaster is a growing community where enthusiasts and professionals alike can find free tutorials on a wide variety of web-based subjects.

Photoshop, Illustrator, website coding and SEO are just a few of the topics. Not only will you see the finished product, but you’ll also learn the techniques needed to produce the final results – all laid out in an easy-to-use, easy-to-understand and, best of all, free, way.

Recent Comments

  • james on - Create a Camera...Oh I'm sorry.. what I mean is, is there a way to automatically save a file to a directory instead of
  • james on - Create a Camera...Can I ask where does the images being saved by the FileReference.save function? Thanks
  • Cody Robertson on - Creating a Upload...@Tutorial City, You have some good points, which are things I would have done if I was doing this