How To Create Your First AJAX and PHP Contact Form

Monday, November 2nd, 2009 Tags: , , ,

You've been to websites that use them, a nice little AJAX contact form. AJAX is a great way to submit data without a page refresh and is a great tool for certain elements of a website, such as a contact form. So how do we go about doing so? Today, we will take it step by step and build your first AJAX and PHP contact form. We'll be using jQuery and the popular email validation code found on google code (originally by AddedBytes) to help us out.


php_ajax_form

Live Demo

Folder Structure and Files

Here is a brief overview of how we will setup our folders and files. If you are following along, you can go ahead and create all of these now, we'll get to them all one by one.

Below is the folder structure and files contained within:

  • assets
    • css
      • style.css
    • js
      • ajax.js
    • php
      • contact-send.php
      • email-validator.php (will be downloaded and added later on)
    • index.html

HTML and Form Markup

Now we need our HTML and form markup. We will try to keep it relatively simple.

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Your First AJAX and PHP Contact Form - Live Demo</title>

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
	<script type="text/javascript" src="assets/js/ajax.js"></script>
	<link rel="stylesheet" type='text/css' href='assets/css/style.css' media='screen' />
</head>

<body>
	<div id='wrap'>
		<div id='header'>
			<h1>Get in touch with us...</h1>
			<h2>Use the form below to try out the contact form.</h2>
		</div>

		<form method='post' action='./assets/php/contact-send.php'>
		<fieldset>
			<legend>Contact Us</legend>
			<label for='name'>Name (required)</label>
				<input id='form_name' type='text' name='name' value='' />
			<label for='email'>Email (required)</label>
				<input id='form_email' type='text' name='email' value='' />
			<label for='subject'>Subject</label>
				<input id='form_subject' type='text' name='subject' value='' />
			<label for='message'>Message (required)</label>
				<textarea id='form_message' rows='10' cols='40' name='message' value=''></textarea>

			<input id='form_submit' type='submit' name='submit' value='Submit' />

			<p class='hide' id='response'></p>

			<div class='hide'>
				<label for='spamCheck'>Do not fill out this field</label>
				<input name='spam_check' type='text' value='' />
			</div>
		</fieldset>
		</form>

	</div>
</body>
</html>

Everything above should look pretty standard, you'll notice we have a weird input and label towards the bottom of the form. We will be using this as a very basic spam check later on. More on that in a bit.

Also take note we are importing jQuery, our soon to be created ajax.js, and our style.css.

Styles

I'll leave the styles up to you, here is the bare minimum. The only thing we really need to make sure is that we hide anything inside the div class of hide. Notice we have still typed

Do not fill out this field

. We've done so in the very rare chance someone is surfing without CSS, they will know to leave the field blank.

style.css

#wrap {
	margin:0 auto;
	width:960px;
}
.hide {
	display: none;
}
label {
	display:block;
}
input {
	display:block;
}

The PHP Code

If you need to brush up on your php skills check out 5 more quality sites to help you become a php rockstar

A word about email validation

You will need to download a file before I go any further, you can download the google email validation script here.

Got it downloaded? Great! Name it email-validator.php and put it in your php folder you created.

Now, a word about email validation. It is tricky business to say the least. There are hundreds if not thousands of little tiny things to take into account. I recently wrote a blog post titled The right way to validate an email address with php. In hindsight, thhe technique used in that post certainly works, but isn't without it's draw backs. FILTER_VALIDATE_EMAIL has known bugs and only runs on newer versions of php, so this isn't an option for a lot of people.

Tired yet? Bare with me.

This is where the google code email validation script we downloaded comes in to play. It originally aired on the well known site AddedBytes.com. It has since grown in popularity so much that it has been moved to google code where it has received hundreds of contributions from members around the world, all with a goal to build a very solid and quick email validation system.

In short, the google email validation script kicks ass and we are going to use it.

Back to the main php code

Now is where we let the php do the heavy lifting. If you haven't already created your contact-send.php file, see the structure above and do so now.

I have left many comments in the code below, so be sure to read through them. I'll go through a few important bullet points after.

contact-send.php

Editors note: Please ignore any duplicate empty function calls below, this is a known bug of the syntax highlighting plugin. You can always download the source files if you have any confusion.

<?php
//Catch any errors while testing our script
//Remove when going live.
ini_set("display_errors", "1");
error_reporting(E_ALL); 

//Ensures no one loads page and does simple spam check.
if(isset($_POST['name']) && empty($_POST['spam_check']))
{
	//Include our email validator for later use
	require 'email-validator.php';
	$validator = new EmailAddressValidator();

	//Declare our $errors variable we will be using later to store any errors.
	$errors = array();

	//Setup our basic variables
	$input_name = strip_tags($_POST['name']);
	$input_email = strip_tags($_POST['email']);
	$input_subject = strip_tags($_POST['subject']);
	$input_message = strip_tags($_POST['message']);

	//We'll check and see if any of the required fields are empty.
	//We use an array to store the required fields.
	$required = array('Name field' => 'name', 'Email field' => 'email', 'Message field' => 'message');

	//Loops through each required $_POST value
	//Checks to ensure it is not empty.
	foreach($required as $key=>$value)
	{
		if(isset($_POST[$value]) && $_POST[$value] !== '')
		{
			continue;
		}
		else {
			$errors[] = $key . ' cannot be left blank';
		}
	}

	//Make sure the email is valid.
    if (!$validator->check_email_address($input_email)) {
           $errors[] = 'Email address is invalid.';
    }

	//Now check to see if there are any errors
	if(empty($errors))
	{

		//No errors, send mail using conditional to ensure it was sent.
		if(mail('fwdrew@gmail.com', "Message from $input_name - $input_subject", $input_message, "From: $input_email"))
		{
			echo 'Your email has been sent.';
		}
		else
		{
			echo 'There was a problem sending your email.';
		}

	}
	else
	{

		//Errors were found, output all errors to the user.
		echo implode('<br />', $errors);

	}
}
else
{
	die('Direct access to this page is not allowed.');
}

Read through the comments thoroughly, most of the code should explain itself.

A few notes:

  • On lines 4-5, we turn error reporting on, this is always a good idea when testing. Remove these lines before going live.
  • On line 8, we ensure that no one loads the page directly, but also do a spam check. When spam bots hit a form they usually fill out all HTML input fields, regardless if they are hidden with css or not. Bots also usually fill in every single input field in hopes of successfully submitting the form. We make sure this field is empty before proceeding. This is a small and basic but effective method against some spam.
  • Lines 11-12 we include and initiate our email validation object.
  • Lines 29-39 check for any empty fields that are required.
  • Line 41-43 Check to see if the email is valid

The rest should make sense.

Right now you have a complete and working contact form. Congratulations! However, we can make this even easier on the end user by using jQuery and a simple AJAX request. jQuery is a Javascript library that allows you to easily do all kinds of cool things, such as quick and easy font resizing and animation.

The jQuery/Javascript

Lets walk through the logic of what we want the jQuery code to do for us, before we start coding it. You'll find this will help you think things through and be more efficient.

  1. Include the jQuery library, we've done so in our head section of our HTML already.
  2. When the form is clicked, ensure that we return false.
  3. Setup our necessary variables holding our form values.
  4. Show the user that work is being done (e.g. Loading...).
  5. Make the AJAX request to our contact-send.php file with input fields as POST data.
  6. Grab the response from the php file, and display it under the form, in the response element we have in our HTML page

Again, I encourage you to go through each line of the code slowly, and read the comments.

ajax.js

$(function(){

	//Do what we need to when form is submitted.
	$('#form_submit').click(function(){

	//Setup any needed variables.
	var input_name = $('#form_name').val(),
		input_email = $('#form_email').val(),
		input_subject = $('#form_subject').val(),
		input_message = $('#form_message').val(),
		response_text = $('#response');
		//Hide any previous response text
		response_text.hide();

		//Change response text to 'loading...'
		response_text.html('Loading...').show();

		//Make AJAX request
		$.post('http://dev-tips.com/demo/ajax_contact_form/assets/php/contact-send.php', {name: input_name, email: input_email, subject: input_subject, message: input_message}, function(data){
			response_text.html(data);
		});

		//Cancel default action
		return false;
	});

});

Obviously, you will want to change the address/location on line 19 to wherever your file is. The rest should be self explanatory.

Works Without Javascript!

Keep in mind a small amount of users wont surf with JavaScript enabled. This means anytime you use AJAX or JavaScript, you need to think about what will happen if JS is disabled. In our case, if JS is disabled, the form will refresh, be validated by php, and send the email if necessary. No worries for us :)

Sit back and relax

If you've been following along this whole time, you can relax and get some bacon now, you've just built a complete AJAX and PHP contact form from scratch!

Comments? Questions? Suggestions? Let me know what you think in the comments section below. And be sure to check out the live demo and/or download all of the files used in this tutorial.

Live Demo

I love Chinese food!

If you found this useful or plan on using this code, will you consider making a donation? I really just want some chicken fried rice.


Tags: , , ,

If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!

ABOUT THIS AUTHOR

Hi, I'm Drew Douglass and I make sure Dev-Tips.com runs smoothly. I also work for Envato Support and write for NETTUTS.com and ThemeForest.net. I'm passionate about anything web development related, especially php, WordPress, MySQL, and jQuery. Feel free to follow me on twitter.
  1. November 2, 2009 at 7:06 am
    • November 2, 2009 at 7:24 am
  2. November 2, 2009 at 9:28 pm
  3. Jon
    November 3, 2009 at 2:11 pm
    • November 3, 2009 at 2:45 pm
      • Jon
        November 3, 2009 at 2:55 pm
  4. November 3, 2009 at 3:00 pm
  5. November 5, 2009 at 11:45 pm
  6. November 6, 2009 at 12:36 am
  7. November 6, 2009 at 12:39 am
  8. Don
    November 6, 2009 at 7:00 am
    • November 6, 2009 at 3:35 pm
  9. Jay
    November 11, 2009 at 3:07 pm
  10. Jay
    November 13, 2009 at 7:43 am
  11. November 17, 2009 at 6:36 pm
    • November 17, 2009 at 9:22 pm
  12. November 30, 2009 at 2:22 am
    • December 1, 2009 at 3:17 pm
  13. Sergiu Naslau
    December 3, 2009 at 7:41 am
  14. December 3, 2009 at 8:35 am
  15. December 7, 2009 at 9:24 am
  16. Sue
    December 18, 2009 at 12:15 pm
    • December 29, 2009 at 7:20 pm
    • December 29, 2009 at 7:21 pm
      • January 3, 2010 at 5:07 pm
  17. nidhalbt
    December 30, 2009 at 3:20 am
  18. January 4, 2010 at 10:09 pm
    • January 4, 2010 at 10:23 pm
  19. January 10, 2010 at 4:35 am
  20. January 11, 2010 at 3:19 pm
  21. January 13, 2010 at 5:46 am
  22. January 29, 2010 at 2:04 am
  23. Mike
    February 15, 2010 at 8:30 pm
  24. Mike
    February 15, 2010 at 8:42 pm
  25. February 16, 2010 at 11:38 am
    • alexut
      March 3, 2010 at 4:20 am
  26. Mike
    February 18, 2010 at 7:18 pm
  27. February 23, 2010 at 8:11 am
    • March 2, 2010 at 1:14 am
      • March 7, 2010 at 10:43 am
  28. vinnie
    March 4, 2010 at 7:27 am

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates