How To Create Your First AJAX and PHP Contact Form
Monday, November 2nd, 2009 Tags: ajax, html, jQuery, PHP
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.

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
- css
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.
- Include the jQuery library, we've done so in our
headsection of our HTML already. - When the form is clicked, ensure that we return false.
- Setup our necessary variables holding our form values.
- Show the user that work is being done (e.g. Loading...).
- Make the AJAX request to our contact-send.php file with input fields as POST data.
- 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.
Usage
You can use this script in any projects or websites you may have, you just cannot sell it as is. Yes, you can use it in commercial products, you just cannot download the script, and then turn around and sell it. Other than that go crazy!
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: ajax, html, jQuery, PHPIf you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!
Article Sponsored by:
PHP for Absolute Beginners is written for the complete novice; no previous coding knowledge is assumed, and all concepts are explained to ensure maximum understanding.
51 Comments
subscribe comments feedTrackbacks/Pingbacks
- uberVU - social comments
- How To Create Your First AJAX and PHP Contact Form | JasonCypret.com
- 120 Tips, Tricks, and Tuts from 2009 Worth your Time « Myblog's Blog
- 120 Tips, Tricks, and Tuts from 2009 Worth your Time | Tutorial51
- Best of 2009 « qeqnes | Designing. jQuery, Ajax, PHP, MySQL and Templates








Wow – what an article, loads of details. I already know that many people (especially those that are new in the AJAX/webdev scene) will love this.
Keep up the great work Drew!
Thanks Marco, really glad you enjoyed it!
Cool, i’ve one using mootools – here is this
http://kodegeek.wordpress.com/2009/06/13/ajax-contact-form-for-your-site/
This is a great contact form, with a minor caveat: seems that it’s still not too protective against spam email. I just put this on my website last night (Nov. 2nd), and I already received a spam message from it this morning. Is there any way to check for links being posted in the message field? It seems that most spam emails have some sort of link in the message field. Can you post a way to give display an error if someone (or a bot) uses “http:” or “www” in the message field?
Hey Jon,
You’re absolutely right. Being as this was a beginner tutorial, I didn’t want to get into a really in depth spam protection system.
To answer your question, yes it is possible to check for a link using regex. A google search will help you more quickly than I.
Perhaps for a next tutorial, we will go into adding more spam defense in the contact form above.
Best of luck.
Drew,
Thanks a lot for that useful bit of information, as well as a quick reply. I’ll definitely look that up right now and give it a go!
Thanks for the great tutorial, it definitely gave me a great start on a nice contact form.
@Jon – You’re quite welcome, glad you enjoyed it
Wondering where you edit the address that the e-mail is sent to…
Line 50 of the php file
thanks =)
For some reason, it is showing the “E-mail sent” on a new page, not in the form. Wonder what I did wrong there? It worked before, but I must have changed something..
http://recording.jseanmcvey.com/assets/index.html/
http://recording.jseanmcvey.com/assets/index.html
Sorry about the slash before.
Think I got it working!
http://recording.jseanmcvey.com/contact.html/?
Thanks for an excellent, no BS and well written walk – through on building a form.
I like your style – thanks also for the code.
Cheers
Thanks for your comment Don, I appreciate the nice words.
Great tutorial.
But I have a problem with “æøå”. In the mail is they showed as æøå
Anyone know how to fix that?
Never mind, fixed it using
$input_message = utf8_decode($_POST['message']);Glad you got it fixed jay
Nice job on this tut Drew! I believe it’s the same as the one you did the screencast over at themeforest, but this is awesome because I don’t have to play a movie
Thanks for this tut! Happy Wordpress coding
Hey Henry! Thanks a bunch, Happy WordPress Coding to you as well
Hi, Just thought I’d let you recognize your website is rendering weird in my K-melleon browser. Looks good from what I can see though.
Thanks for the heads up, I’ll have to take a look sometime
the focus of the forms is done by jquery? don;t se it done in the css
Thanks this was a good read
Hey,
thanks thats made it alot easier,
I was wondering how to make another field that could enclude a telephone number, I tried copying and pasting but it doesnt work.
Carl
OK…I didn’t change anything…but I guess I should have. What’s up with this error>
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /home5/waitegen/public_html/suewaitelangley/CulinaryChoices/ajax_contact_form/assets/php/email-validator.php on line 27
The test form is at http://suewaitelangley.com/CulinaryChoices/ajax_contact_form/index.html
Line 27 states public function check_email_address($strEmailAddress) {
ANY HELP on what to do next would be wonderful! THANKS
Does anyone have an answer to this?? I am having the same problem, except the url is different. I searched my entire site and i could not find the url in any code. I dont know much javascript or php. Im only a designer.
Thanks!
Does anyone have an answer to this?? I am having the same problem, except the url is different. I searched my entire site and i could not find the url in any code. I dont know much javascript or php. Im only a designer.
Thanks!
url:
http://www.breuben.com/contact.html
I believe this is related to the email validation class we are using and your server settings. Are you running an older version of PHP?
Thanks buddy
You can’t imagine how good this tip was for me
V
Glad it could help
Great tutorial. I just wanted to clarify something, from the usage statement above it looks like I can but am I allowed to integrate this code with a themeforest theme to sell? I will probably be making a couple more edits to the scripts and css before I sell.
Thanks
Hi Aegnus,
You have my permission to use this script in a ThemeForest theme provided you provide a link somewhere in the documentation of your item.
You can give the reviewers a link to this comment if you like, I’m actually part of the Envato support team
Hey Drew!
Nice tut you have there.
I have a little problem though.
The script works just find on my template, for testing purposes I’ve entered my private email as receiver, but I’m not receiving the email?
Where can the problem be?
Thanks!
very interesting, though I use lynx as browser thus ajax isn’t much helpful
Ok, found it! mail was in my spam box
I’ve been looking for this exact information on this subject for a long time.
How would you go about clearing the form fields after submission instead of keeping them populated?
Another issue I am having is that my form is in my footer, and when I hit submit, if there are errors. it scrolls back up to the top of the page, is there a way to keep it anchored?
Great tutorial, incredibly helpful!
Is anyone having any issues with this in IE or in Firefox?
For me I just get the ‘Loading…’ message every time I hit the submit button and in IE instead of loading the ‘Your email has been sent.’ or error messages it take me to a new, unformatted page that tells me the same info.
I’m also wondering how I would go about putting in additional text inputs and how I would go about getting those included in the email message.
I’m fairly inexperienced when it comes to PHP/AJAX/forms so Any help would be greatly appreciated.
i’m having the same issue
I should have clarified better, for my PHP, I am assigning my error messages to variables to echo out, rather than just using echo, is there a way to pass these into the JS to be used?
Hi,
Thanks for the script, Drew, it’s really simple and powerful!
BUT… I’m not sure what happens for users with JS disabled: I’ve tried disabling JS in IE8, and the submit seems to lead directly to contact-send.php – which returns “Direct access to this page is not allowed.”.
Can someone out here:
- confirm the “Direct access to this page is not allowed.” message means no form validation is actually done without JS?
- provide me with the easy-to-implement-and-yet-highly-reliable way to allow people without JS to validate the form?
Thanks,
David
Either way the form and information is still posted to the PHP file, so it will work without JS if setup correctly.
That’s what I thought should happen… But then, I must have done something wrong while implementing the form on my website http://www.commeunsigne.fr
If you have a few minutes spare, would you mind just giving it a look?
Thanks a lot!
You’re the man dude!
Cheers.