May
1
2010
jQuery // PHP // script // web

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 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="js/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 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>Thanks! Your message has been sent.</p>
    <p id="sendError">There was an error sending your message.</p>
    <p id="emailError">Please enter a valid email address.</p>
    <p id="nameError">Please enter your name.</p>
    <p id="commentError">Please enter a message.</p>

  <form action="send.php" method="post" name="contactForm" id="contactForm">
  <p><input name="name" id="name" type="text" size="30" value="Your Name" onfocus="this.value=''" /><label for="name"></label></p>
  <p><input name="email" id="email" type="text" size="30" value="Your Email Address" onfocus="this.value=''" /><label for="name"></label></p>
  <p><textarea name="comment" id="comment" rows="5" cols="40" onclick="javascript:this.value=''">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:30px;
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:10px;
-moz-border-radius:10px;
-webkit-border-radius:10px;
padding: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');

	});

	// when the Submit button is clicked...
	$('input#submit').click(function() {

		// Gather data from the form
		var name = $('#name').val();
		var email = $('#email').val();
		var comment = $('#comment').val();

		// Regular expression to check the email address
		var emailOK = /[A-Za-z0-9._-]+@[A-Za-z0-9_-]+.([a-zA-Z.]{2,5})/.test(email);

		// series of checks to make sure name and comment are not blank
		if (name != '') { //make sure name field is not blank.
			if (comment != '') { // make sure comment field is not blank
	        	if (emailOK == true) { // make sure email passed the regex check.
	        		// if all checks as passed, run ajax object.
	        		$.ajax({
	        			type: "post",
						url: "send.php",
						data: "name=" + name + "&amp;email=" + email + "&amp;comment=" + comment,
						error: function() {
							$('.error').hide();
							$('#sendError').slideDown('slow');
						},
						success: function () {
							$('.error').hide();
							$('.success').slideDown('slow');
							$('form#contactForm').fadeOut('slow');
						}
	        		});
	        	}
				else {
					$('.error').hide();
					$('#emailError').slideDown('slow');
				}
			}
			else {
				$('.error').hide();
				$('#commentError').slideDown('slow');
			}
		} else {
			$('.error').hide();
			$('#nameError').slideDown('slow');
		}
		// stop the form from doing its default action
		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

// Collect POST data from form
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];

// Define email variables
$message = date('d/m/Y')."n".$name." (".$email.") sent the following comment:n".$comment;
$to = "web@beautilitydesign.co.uk";
$subject = "Contact from Beautility website.";
$headers = 'From: '.$email.'rn'Reply-To: '.$email.'rn'X-Mailer: PHP/'.phpversion();

// Send the  mail
mail($to, $subject, $message, $headers);
?>

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

download live demo

1 Comment + Add Comment

  • getting invalid name and invalid email address all the time

Leave a comment