jQuery AJAX Contact Form
Posted: October 5th, 2008 | Author: Bryan | Filed under: Coding, Tutorial | 80 Comments »Today I am going to speak a little bit about a quick and easy way to make a jQuery AJAX Contact Form that employs a honeypot to foil pesky email bots. You can also check out the demo here to get an idea of how the end product will act. You can use the form anywhere you like, but a courtesy link somewhere is appreciated. It is released under the Creative Commons Attribution License. Let’s rundown the goals:
- A safe form with sanitation.
- Load success or error messages dynamically without leaving the page.
- Descriptive error messages detailing why the entered values failed validation.
- A honeypot to beat the bots.
That may sound like quite a tall order, but in fact, it can be put together fairly quickly with the tools that are available online. If you don’t feel like learning about how to create a form and just want the form. Go ahead and download it here, be sure to change the html to sendmail.php and the email address in the same file. Other wise, read on!
First, let’s talk about jQuery and company.
jQuery is a popular javascript framework with powerful tools to help developers write code and develop products faster. There are a ton of popular plugins, and the one I will highlight for use today is the jQuery Form Plugin. This plugin is great because by simply adding the the jQuery library and the plugin, you can AJAX’ify pretty much any form without much work. However, this results in a rather crude contact form and we can do much better with a little tweaking!
Getting started with the browser side.
First, download the jQuery library and form plugin and then let’s start creating our HTML form. Keep them all in the same folder for now. We’ll want to first call both javascript files, let’s do that with:
That’s a great start, but we need to make the form before we can customize our javascript to fit the form. Here is a sample form to get us started:
We have several fields in this form, one for a name, email, telephone number and message. The field marked “last” and “Don’t fill this in:” is the honey pot! The idea is that this will be hidden with CSS with the a line like this:
li.special {
display:none;
}
This should keep humans from entering any value into the field. If a value is entered (by a bot), then the PHP script will recognize this and won’t send out an email.
Now that we have our form it’s time to customize that javascript! Go back to the head of your html file:
Now we have lots more code to talk about! The first bit simply says that the target div for updating dynamically with the echoed stuff from php is “#alert”. The last little bit says that “#contactForm” is the target of the submit! Check it our here:
$(document).ready(function() {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
Now the next little function simply clears all of the fields on the form, helping reduce an accidental double click of the submit button. It will be called via a PHP echo after the submit button is clicked:
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
That should pretty much do it for HTML side, minus the CSS needed to format it. Make sure to download the demo file here to get all the files and full code. Time to get into the meat of the project and do the PHP!
Getting started with the server side.
There is quite a bit of PHP that will be require to do all this! So let’s put it together in steps, let’s first start by making a function to sanitize the variables for any dangerous characters. We’ll use it later in when we are ready to send the email.
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
Now we’ll want to check the “last” variable (the honeypot), if it isn’t empty, we’ll skip the mail function and echo a message:
if ( empty($_REQUEST['last']) ) {
//rest of code will go here!
} else {
echo "";
echo $honeypot;
}
Assuming the honeypot is empty, we now need to check the variables to see if they are formatted correctly. We’ll do that by checking if their empty and if not, their format. If they fail either test, we’ll return an appropriate error message and flip a variable telling the server to send the error message instead of sending the email to us! This is how we’ll do that for the name:
if ( empty($_REQUEST['name']) ) { //check if its empty
$pass = 1; //flip the variable, send an error message!
$alert .= "
Now a similar format is followed for the rest of the variables, with different validation checks:
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "
I think you get the idea! Each error message is encapsulated in a list tag and it appended to the $alert variable. By the end of the run, $alert should contain a string of all the appropriate (if any) error messages which we can then relay to the user. We do that by checking to see if the $pass variable has flipped:
if ( $pass==1 ) {
echo ""; //js for the error message effect
echo "" . $errormessage . "";
echo "
- "; //starting the list
echo $alert; //echo the error messages
echo "
Now, for the final addition, let’s send that email. We’ll want to use the “mail” function in PHP to do this because it’s simple and quick. We’ll employ the “clean_var” function to sanitize the user entered data. Here it is:
///this is earlier error code
} elseif (isset($_REQUEST['message'])) {
$message = "From: " . clean_var($_REQUEST['name']) . "n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "n";
$message .= "Telephone: " . clean_var($_REQUEST['tele']) . "n";
$message .= "Message: n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
mail($sendto, $subject, $message, $header);
echo "";
echo $thanks;
die();
}
That should just about wrap it up besides for the variables we should set at the beginning of the code. Here they are in all their glory:
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'youremail@example.com';
// The subject you'll see in your inbox
$subject = 'Contact from contact form';
// Message if there isn't a mail function
$mailerror = "Oops! It seems that the server can't mail this! Try emailing us at " . $sendto . " instead.";
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email! We'll get back to you as soon as possible!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptytele = 'Entering your telephone number?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: name@example.com?';
$alerttele = 'Entering your telephone number in this format: 555-555-5555?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
$alert = ''; // Got to call it first in order to append the error messages
$pass = 0; // Default is pass through, errors will flip
Phew! Now that was a lot of code! If this is too much to deal with right, just download the zipped file and get all of the code, html and CSS together.
If you catch any error or bloopers, please let me know! I stuck this together really quickly and I am bound to make mistakes. Thanks guys!
Great form, I’m using it on a website I’m doing.
http://www.mrshiftit.co.nz
Only problem is IE6, the ajax doesn’t load.
Nice form and I’ll continue using it regardless.
IE6 is always a problem… Let me do some quick reviewing here and see if I can get it to work.
It should still work regardless, it just won’t be fancy like in more competent browsers.
is there any way to make this form work in ie 6
Unfortunately, there isn’t at the moment, just another little bug.
I’m trying to fix it but it seems that the AJAX is the problem, you can still use the form, it just loses its AJAX coolness.
We should just promote firefox for viewers I still see no point using ie…
Great form and like how you provide the lazy download and the tutorial for those of us that want to learn. hehe
thanks
hey does this work out the box? I downloaded it and changed the send to what else do I have to change?
The only other thing you should have to do is adjust the “formaction=” to hit the correct php file.
Also, make sure to include both JS files in the header.
Should work!
The form is most liekly broken in ie because of the following entry
var options = {
target: ‘#alert’,
};
remove the , after alert. The comma is only needed if you plan to add a second var. This will cause javascript errors in ie and is why it loses the ajaxyness.
Good catch Pete, appreciate the eyes. I have IE7 on this particular computer so I can’t verify this, but once I do, I’ll update it again.
Thanks for the eyes.
hmm i did those two things and i tested on two of my ftps and I am not getting the mail
http://your-memory.net/pinnaclesolutions/ajaxcontactformv1/
thats the link
just an update I did get it working… I downloaded the demo frm the bottom of the page. Great tutorial mate I want to do it from scratch when I have some time keep up the good work
Hi, very good contact form. Works great, but what about special carateres. Here in France, we have many “é è ‘ ? ! à ç” etc…. If I type those in the message it tells me it won’t send. but without those, word make no sense in french.
How can I add these letters ? Thanks
Sapin, it would involve the regular expressions for the message or name field.
I recommend you look for a regular expression list for French or something similar. Then simply open the php file and replace the appropriate ereg expressions.
You could also erase the esleif { … } statement for the name and message as well just to make sure that it is filled, then it won’t check against a character set.
Excellent. Thanks for the tip. Wonderful tool.
I uploaded all the files, kept the formaction to sendmailexample.php and changed the $sendto to my email address within that file. I tried with two email addresses and i’m not getting the email.
Anything else I need to check?
You need to change the sendmailexample.php to sendmail.php. Also you need to change the email address in the sendmail.php.
Should work!
Thanks for the tutorial! However, in my google search, I noticed that this tutorial content was copied over on this web design blog:
http://blog.branding-studio.com/2008/10/jquery-ajax-contact-form/
His post was dated after yours and yours rank much higher in the google results, so I am assuming you are the originator!
Nice articlte and good explanation
Hi, I can’t understand why the form redirect to the sendmail.php page and do not apply the effect, but only with IE7 of course.
If you could have a look at (http://rotoplus.net/nautylys/?static3/contact)
to see if you can debug this, I would appreciate.
Thnaks
Thanks for the source codes.
This is really a great plug-in. Thanks for sharing it! I am wondering, though, is there a callback function? Basically I’d like to be able to customize the validation and submit responses. In some cases, I’d want to like up a dialog window in others I would want to just display the error messages to the right of or below the text fields. I just now downloaded everything but am going to take a look at the code and see what I can do. In the meantime, any ideas to this end?
Hello again,
Ok I found what I was looking for in the sendmail.php file. Basically I’m altering it a bit to open up a dialog with the error / success messages. I’m new to .php in general and am wondering wow are you able to use jQuery functions within the .php file? When you insert jQuery into the document that somehow gives you access to it in the .php file?
Thanks…
thanks for this script.
i found what has to be replaced for the accents to work.
on line 105:
} elseif ( eregi( “^[a-z0-9_\xC0-\xFF-]+$”, $_REQUEST['name'] ) ) {
on line 129:
} elseif ( eregi( “^[a-z0-9_\xC0-\xFF-]+$”, $_REQUEST['message'] ) ) {
Wonderful!Thanks!
Pete said at 4:10 pm on October 20th, 2008:
The form is most liekly broken in ie because of the following entry
var options = {
target: ‘#alert’,
};
He is right. Remove the comma after ‘alert’ and you’re set. Otherwise, IE6 will load sendmail.php and that means no AJAX really… just a regular FORM.
wow, you saved me a ton of headache with this. Thank you so much. (Sorry nothing constructive to add other than a thanks)
Great tutorial!
I’m trying to use this in a site now and I’m getting an error:
“Making sure you aren’t using any parenthesis or other escaping characters in the message? Most URLS are fine though!”
I can only assume this is because I’ve added cols to my textarea. I’m guessing the cols are adding newline characters or some other type of character that the php file is throwing an error at.
Any idea how to remedy this?
Thanks.
Thanks for tutorial !
I’ve never been working with jQuery before. But I love the tutorial. One thing though. How the hell do I change the animation of #alert? Want it to simply fade in from display:none? Please, give me a hand.
hey I love this tutorial great but I have been trying to take it apart because I want the errors to show under the individual text boxes so far i have had no luck=(… any hints?
Kickass Form – Just what I´m looking for!
However, I am trying to do a sidebar with a lot of diferent forms for registrations, member info changes and so on. I have managed to get multiple forms working fine, that is, the same set of fields.
But I want to do different fields for all the forms and some drop down lists etc. How can I do this? By the way – I know nothing of PHP, nothing worth mentioning.
Please help me.
I am using, with success this script on a few sites. I am frustrated in my attempt to use this multiple times on the same contact page. The first submit works the ajax sweetly, however the second submit breaks the ajax coolness. I am using 2 sendmail.php files , one for each email. what am I doing wrong. do I need to have discrete forms for each?
This is great! Thanks for giving us this example. The only thing is that the message appears at the beginning and the end of the email when I receive it. Am I the only one who is having this problem?
it nice! but not work with IE 7.so i try your demo with IE.
Thanks , thays just what i need!
One question, when the form is not valid i want the menssage show stylezed with red colors, ok thats i do! But now i whant to put green colors on the whem the form is correct.
How i do that? I can use o remove and add class functions? If yes where i put them and how?
Thanks.
Got a problem, maybe someone can give me some insight on what the issue is and how I can fix it.
Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\3497744\html\sendmail.php on line 151
Problem was fixed by changing /n with /r/n.
Hi,
I had a problem getting jquery form plugin to submit in ie6, i found by adding onclick=”" to the submit input tag ie6 behaved itself, hope that helps someone else out
muchas gracias, me sirvio y esta funcionando muy bien. Gracias!
como podria hacer una aporte a su página via paypal o algún otro método??
Great tutorial. Everything works great except for the AJAX portion in IE7. I tried removing the comma as the one comment suggested, but that still didn’t work. Is anyone else having the same troubles?
Just wanted to say thank you so much! This is a great script!
This is great! The only thing is that I need to redirect to a thank you page…is there a way to do that with this form?
@Todd same here, IE7 doesn’t seem to work, both the mail sending and the jquery “reply”
also tried the comma solution, but nothing, anyone?
Really good explanation, many thanks!
This is one excellent looking theme. It really does have some nice features. Great work!
If you already have a php script for form processing but would like to add your jquery method to it what part of the script would need changing in order to accomplish this? The form is http://www.tectite.com/
Hi,
Everything seems to work fine except that the email is not received.
I changed the sendemailexample.php to enter my email id. But for some reason emails are got.
In Ie7 i get an error saying thread did not exit()
I meant to say that emails are lost. I dont get any emails.
hey there, great script.
i try to use it in a wordpress developpement. I receive the mail without problems but i just cant get the animations. It keeps sending me to another page to display the informations that should come above the form with the js effects.
My links to jquery, jquery.form.js are both checked and good, as well as css.
Any idea ?
hi again, i found the solution, stupid mistake from me. Works great within my wordpress theme. Messages can be deleted if moderators wish so.
Thanks for script anyway, great help.
How are you getting the error messages to scroll into view?
Thanx Buddy
WooT!
Nice work!
Works like it should, good to style.
And like pete said! remove the “,” (komma) after ‘#alert’ in your head (the javascript), cause IE6&7 won’t eat that, since they expect more to happen.
Cool!
thanks!
hey, me again,
just did another test and it sends me an email without caring about the accents on letters. For ex, i should get: “ã” and i get “ã” instead. Any idea why i cant get the accents ?
Am struggling on that cos i use the script in a portuguese site and there are lots of accents.
Fixed, with this line:
$header = “Content-Type: text/html; charset=UTF-8\n”;
Hi and THANK YOU for this great script but I don’t get it why it doesn’t work. I mean everything is ok and no errors but I don’t receive any mails.
On my server I have installed the latest WordPress version, I had some old websites with pages with other php contact forms that worked, I have read all again to see if I forgot anything…I just don’t receive the mail.
I tried with a Gmail address, Yahoo and the one i got with my hosting account – no mails. Is there any other reasons then missing something to set up?
Thank you.
[...] 8. jQuery AJAX Contact Form Here is a quick and easy way to make a jQuery AJAX contact form with a “honeypot” to foil email bots, load success and error messages dynamically without leaving the page and provide descriptive error messages detailing why submitted values have failed validation. [...]
Easy and comfortable contact form. Thank you!
Works perfectly , but i can’t get the correct information from ajax form. Some characters (çşüöğı) are NOT viewing fine. For example:göktürk , ÅŸendoÄŸan. How I can fix that?
Great stuff. Although I’m a not a fgan of your validation with php, as it seems a bit clumsey imo.
Thanks for a great script – works great!!
For the character set problem the best solution is to use the \w character class in the regex instead of trying to include all possible characters: \w is locale-specific in PCRE (the library PHP uses for preg_match and its friends) so if you use the correct locale it will automatically allow all word-type characters. You’ll have to use preg_match rather than eregi (which is anyhow deprecated from PHP 5.3.0), so check your regex syntax for the right flavour.
Great form, like the honeypot idea. I wonder why you don’t do most of your validation in jQuery though, is there some reason to do it in php that I’m not aware of?
I am trying to remove the validation for the “messege” filed but it keeps poping up any ideas?
Hi,
How do you go about adding radio buttons to this?
I would like to add a male or female field on my form but cant seem to get it working.
Any help would be much appreciated.
Great script!
Great script and it works perfect,Thanks. I have something to share AJAX Registration no need to code http://www.phpstring.co.cc/ajax-registration-module/
Hi, nice form!
I live in Quebec (canada) and there are a lot of french speaking people here.
Someone suggested changing 2 lines of code, but it doesnt work for me. Is there a simple way of doing this? I would love to use this form.
Thanks for the tutorial, but i cant seem to read the text for the code on your web page. Too small.
I had to take the lazy route and download the demo.
Hello,
I must retarded or something, followed the instructions to the letter and nothing. The form works, but I can’t any emails and yes I did changed the email and the link to the sendemail.php document.
Please help.
For those having a problem with IE6.
var options = {
target: ‘#alert’,
};
Remove the comma after ‘#alert’
How can I change the email address from the sender? It is now login-name@domain.com
but i want it to change to info@domain.com.
I am using this script for a clients website.
I would like to add html formatting for the email output…
Also, I would like a copy of the message to be sent to the person who fills out the field…
Does anyone want to help me?
This is a great tutorial, but I can’t figure out how to make it work if you don’t need a telephone number or a message. I tried commenting those parts out of the PHP file, but that made the file just not do anything when I pressed the button. How do you take out the parts you don’t need?
[...] 8. jQuery AJAX Contact Form Here is a quick and easy way to make a jQuery AJAX contact form with a “honeypot” to foil email bots, load success and error messages dynamically without leaving the page and provide descriptive error messages detailing why submitted values have failed validation. [...]
Thank You! Great contact form jquery script. Very easy and helpful!
Hi I am using Google Chrome to view this page and for some reason the code is very, very small – unreadable. Is this a CSS issue, and if you notice the same thing I’d recommend you fix it. Otherwise good tutorial,
Thanks,
Thanks SO MUCH for the plugin… Great work! I removed the comma after alert and all is kewl with IE7 now. I also modified my version to send multiple emails from one form. Your insights and work are greatly appreciated!
well I downloaded it now and am digging it for my website
Sorry, didn’t work for me: The Button is not responding.. looked for 2 hours for the causing and read the replies to this article twice.
Had tried several other options from the internet and was on the verge of despair.
This form here works right out of the box.
Thanks so much.