PHP Contact Form with jQuery Validation

09 April 2009 ~ 276 Comments

Hi there! You need a jQuery contact form for your website but don’t know how to create one? Please read along and maybe you’ll get lucky. A contact form is very helpful in giving your visitors a way to contact you. In this tutorial, I will help you on how to create your own jQuery contact form using PHP and JQuery.

Let’s start with the basics. We only need a single page for our contact form and this page will contain the markup, PHP to process our contact form and JQuery validating. For those who need to see a working demo of the jQuery contact form, you can check it out here.

Step One: jQuery Contact Form Markup

First, let’s create the markup for our contact form. Create a new page called contact.php (or whatever name you want as long as it has a PHP extension). Having a PHP file affords us the luxury of only having a single page to display and at the same time process our contact form. We also used a PHP constant for the action value of our contact form. That constant is the filename of the current file, relative to the document root. This is to ensure us that our form will go to the same page after sending our form.

<!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>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

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

	<style type="text/css">

	</style>
</head>

<body>
<div id="contact-wrapper">
	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
</div>
</body>
</html>

Step Two: Give it some style

We’re going to apply some styling to our contact form using CSS to make it more interesting. For the purposes of this tutorial we’re going to embed our CSS right inside contact.php inside the head section and in between the style tags.

body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}

If you’re following along, your contact form should look like this:
contactform screenshot

Step Three: Validate using JQuery

We already loaded JQuery in case you haven’t noticed in our initial contact form markup:

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

Loading JQuery alone only gets half of the job done. We still need a JQuery plugin called Validation to help us validate our contact form. After you’ve downloaded and extracted the plugin, look for jquery.validate.pack.js file and save it where your contact.php is saved and reference it from the file just like what you did with JQuery.

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

Now we need to initialize the JQuery:Validation plugin in order to use it. Take note that #contactform is the id value of the form.

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

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

After that, we now need to add a class attribute to our input fields. If you just need a required field you just add class=”required” to the input tag and when you need to require and validate an email so that the format is correct then you need to add class=”required email”. Here’s the updated markup for our jQuery contact form with the classes already added.

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
	<div>
	    <label for="name"><strong>Name:</strong></label>
		<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
	</div>

	<div>
		<label for="email"><strong>Email:</strong></label>
		<input type="text" size="50" name="email" id="email" value="" class="required email" />
	</div>

	<div>
		<label for="subject"><strong>Subject:</strong></label>
		<input type="text" size="50" name="subject" id="subject" value="" class="required" />
	</div>

	<div>
		<label for="message"><strong>Message:</strong></label>
		<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
	</div>
    <input type="submit" value="Send Message" name="submit" />
</form>

Now refresh your jQuery contact page and submit the contact form without entering any data. Your contact page will catch the errors and hopefully will look like the image below. Also try entering a different format for the email field and you should see a different message. Try reading the Validation documentation for more validation options.

contact form with validation

Step Four: Submit and process the form using PHP

Now it’s time to add some PHP magic to our jQuery contact form! Place this code on the topmost section of your file (just above your DOCTYPE declaration). You might be wondering why we need to validate the inputs again even if we already validated the inputs using Javascript. The reason is that PHP will act as our second level of validation in case Javascript is turned off on the client’s machine. I highly suggest that you don’t rely on Javascript alone for validating form inputs. Aside from validating inputs, PHP will also be responsible for sending out the email in case no errors were found.

I’ve stripped down and borrowed the code below from this very helpful article. The green comments should basically explain what each code snippet is doing.

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>

We’re almost finished! All we have to do is insert a little more PHP to output two kinds of messages. The first message is to notify us in case there were errors after our submission, and the other is a message to tell us that the email was already sent and no errors were found. The code for that will just sit right inside the contact-wrapper div but right before the jQuery contact form markup.

<?php if(isset($hasError)) { //If errors are found ?>
	<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>

<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
	<p><strong>Email Successfully Sent!</strong></p>
	<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
<?php } ?>

Finished Code

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>
<!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>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

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

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

<style type="text/css">
body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}
</style>
</head>

<body>
	<div id="contact-wrapper">

	<?php if(isset($hasError)) { //If errors are found ?>
		<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
	<?php } ?>

	<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
		<p><strong>Email Successfully Sent!</strong></p>
		<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
	<?php } ?>

	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" class="required email" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" class="required" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
	</div>
</body>
</html>

We are Done!

You have created a jQuery contact form using PHP and JQuery for validation all contained in a single page! All you have to do is put your email address in line 41 and off you go! Great job! I hope you will find this tutorial helpful as I’ve carefully detailed all the steps needed to create our contact form. Please tell me what you think and I would appreciate your comment. Thank you so much for reading and hope to see you again.

276 Responses to “PHP Contact Form with jQuery Validation”

  1. We Love Webdesign 10 April 2009 at 10:00 pm Permalink

    Hi, Great tutorial. Thank you !

    I prefer to use the tag : fieldset instead of div to wrap a group of related label / input. I think it’s more semantic.

  2. Jason Armstrong 10 April 2009 at 11:30 pm Permalink

    Great tutorial! Thanks so much for sharing!

  3. Raymond Selda 11 April 2009 at 1:02 am Permalink

    @We Love Webdesign: Thank you for the comment. You are absolutely right on using fieldset instead of a div for wrapping up the form. My bad! hahaha.

    @Jason Armstrong: Thank you for your comment.

  4. Patternhead 11 April 2009 at 6:00 pm Permalink

    Nice tut, thanks :)

  5. Nihar 12 April 2009 at 1:37 pm Permalink

    Great… Thanks for the wonderful tutorial.

  6. Jitendra Vyas 15 April 2009 at 4:38 pm Permalink

    I changed the email address to mine but mailnot coming to my email

  7. Raymond Selda 15 April 2009 at 4:44 pm Permalink

    @Jitendra Vyas: Please check your spam folder. I noticed that Gmail tends to classify the email as spam. I tried using a Yahoo mail and everything was sent to my inbox. I guess this has something to do with the headers from the email.

  8. Jitendra Vyas 15 April 2009 at 4:52 pm Permalink

    Already checked spam folder nothing was there but your comment has come in spam not inbox .

    I just replaced this $emailTo = ‘youremail@yoursite.com’; to $emailTo = ‘myemail address’;

    http://jitendravyas.com/contact/scripts/contact.php

  9. Richard Le Poidevin 17 April 2009 at 11:32 pm Permalink

    You might want to wrap the input in the label tag too. Some people prefer that method, however you’d need to wrap the label’s text in another tag, or add some more styling to the strong tag to format it in the correct manner.

    Ideally you’d submit the form to another php page too, because if someone refreshes after sending an email it’ll send it again.

  10. Max Lim 20 April 2009 at 2:16 pm Permalink

    Hi. I like the article, but I have got question.
    Why do you use jQuery from google ? You can put on your web server.

  11. Raymond Selda 20 April 2009 at 3:52 pm Permalink

    @Max Lim: There are 3 reasons why you want to let Google host JQuery for you.

    1. Decreased latency
    2. Increased parallelism and
    3. Better Caching (my favorite)

    For a better explanation on each of them please visit http://tinyurl.com/657z83

    Thank you.

  12. Chris 22 April 2009 at 11:03 am Permalink

    Good work – nice post!

  13. saurabh shah 1 May 2009 at 11:03 pm Permalink

    nice article .. and yes ! very handy and helpful .. thanks for sharing…

  14. biuuu 4 May 2009 at 1:48 pm Permalink

    very good!
    thank you

  15. Mariano Siffredi 16 May 2009 at 1:50 pm Permalink

    I copied and pasted the code exactly from the ‘Finished Code’ step, changed $emailTo = ‘youremail@yoursite.com’; using my own e-mail and also checked that the path for the js links were correctly but, when I tested it, it just didn’t work. Some help needed. http://www.danalberto.com/danalberto/contact.php

  16. Raymond Selda 16 May 2009 at 2:17 pm Permalink

    Hello Mariano,

    I’m here to help. What do you mean by “it just didn’t work”? What message did you get after you submit the contact form? Did you get the info details from the contact form to your email? I sent a message using the contact form you provided in the link and I got a confirmation message that my email was sent.

    I also tried what you did by copying the finished code. I changed the email and it worked out just fine.

    I can help you more if you can provide additional details. Thanks.

  17. Mariano Siffredi 16 May 2009 at 2:49 pm Permalink

    Ok, I didn’t received the e-mail supposed to be delivered by the form. Thank you!

  18. Raymond Selda 16 May 2009 at 3:07 pm Permalink

    Try checking your spam folder. If nothing really works out just double check everything and try out different email addresses or just try different approaches. Sometimes you really have to troubleshoot in order to find out what’s really happening. Thank you and good luck

  19. Randy 21 May 2009 at 10:57 am Permalink

    Great Tutorial!

    I was just wondering if i could put the PHP code in a seperate file and include that file into my HTML file?

    If so how may i go about doing it?

  20. Raymond Selda 21 May 2009 at 12:28 pm Permalink

    @Randy: Yes, you could try putting the PHP code into another file then include it at the topmost part of the file that displays the form. Just make sure that all files are in PHP. Let me know if you’re successful with that. Thanks.

  21. apad 26 May 2009 at 10:50 pm Permalink

    Thanks for the tutorial. Now i am implementing most of your code within my client website! as they doesn’t require a very dynamic website (which i prefer to use WordPress, usually), your code seem to fit the bill for most of the basic website need today. Thanks Raymond!

  22. Raymond Selda 26 May 2009 at 11:19 pm Permalink

    You’re welcome Apad. I’m glad my contact form was useful. :-)

  23. Shaun Scott 3 June 2009 at 1:38 am Permalink

    Great tutorial….really helpful! I have a question….how would i add and send “auto reply” message to the end-user? I’m fairly new to PHP!

    Thanks for you help in advance!

  24. Raymond Selda 3 June 2009 at 8:43 am Permalink

    @Shaun: You can add the “auto reply” message by writing another mail function that will send a message to the user. I hope that made sense. Thanks for your comment.

  25. Shaun Scott 13 June 2009 at 2:22 am Permalink

    thanks for the reply….as i said i’m a bit new to new to PHP and as it does make sense…i’ve tried to pull it off but it’s not working for me…here’s my example:

    $emailTo = 'info@jac-n-rum.com' . ', ';//email to info
    $emailTo .= 'jacnrum@gmail.com';
    $body = "Subject: $subject \n\nFirst Name: $name \n\nLast Name: $lname \n\nAddtional Guest: $addguest \n\nEmail: $email \n\nComments:\n $comments";
    $headers = 'From: '.$name.' '.$lname.' '; //(for reply to) . "\r\n" . 'Reply-To: ' . $email
    mail($emailTo, $subject, $body, $headers);


    $to = '$email';
    $subject = 'My subject';
    $message = 'Hello world!';
    $headers .= 'info@jac-n-rum.com';
    mail($to, $subject, $message, $headers);

    $emailSent = true;

    can you tell me what i may be doing wrong?

    thanks in advance!

  26. Raymond Selda 13 June 2009 at 8:35 am Permalink

    @Shaun: Glad to know you’re trying things out and making it happen. I like your idea and I know you can make it work. I tried the same thing and this is what I came up with:


    $emailTo = 'mywonderfulemail@gmail.com'; //Put your own email address here
    $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
    $headers = 'From: My Site < '.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
    mail($emailTo, $subject, $body, $headers);


    $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
    $headers = 'From: domain.com < '.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
    mail($email, $subject, $body, $headers);

    $emailSent = true;

    I put the $email directly into the second mail function. This one works with both gmail and yahoo. Try this one and let me know how you kicked ass! :-)

  27. Shaun Scott 20 June 2009 at 2:21 pm Permalink

    i “guess” i was close…lol!

    Thanks so much for your help…you’ve been a great help! Keep up the great work!

  28. Raymond Selda 20 June 2009 at 4:42 pm Permalink

    You’re welcome Shaun. Glad to be helpful. Thanks and keep on coding.

  29. Abreu 1 July 2009 at 11:16 pm Permalink

    Hi, Raymond,

    I used your code in my project, but the request field text: “This field is required.” is in english, but i need put in portuguese. Did you help me please, how do that?

    Best regards and good work!
    Abreu

  30. Raymond Selda 1 July 2009 at 11:38 pm Permalink

    Hi Abreu,

    Please visit the plugin documentation here: http://docs.jquery.com/Plugins/Validation/validate#options

    Click on the “Options” tab then scroll down and look for messages. I think you can specify your custom messages with that option.

    Good luck.

  31. Abreu 2 July 2009 at 12:03 am Permalink

    thanks! ;)

  32. Rudi 3 July 2009 at 10:06 am Permalink

    Thx for this useful tutorial man,

  33. Scott Cooper 8 July 2009 at 8:04 am Permalink

    Hi Raymond,

    I was wondering if Randy got it working linking it to a Contact.html page rather than PHP page?

    We’re working on a site that doesn’t have PHP on the hosting but just want to point the form to execute on another server location that has PHP hosting.

    Example:
    Contact.html will be part of the site. And form to post through to contact-form.php on another server

    I’d like to do it this way rather than using an iFrame. Have you any suggestions apart from just making the files PHP?

    Thanks,
    Scott

    @Randy: Yes, you could try putting the PHP code into another file then include it at the topmost part of the file that displays the form. Just make sure that all files are in PHP. Let me know if you’re successful with that. Thanks.

  34. Raymond Selda 8 July 2009 at 5:24 pm Permalink

    Hi Scott,

    I think you cannot call it from another server. The files should reside in the same server. If you don’t have PHP in your server, you could try to process the form the old school way by using CGI. I never tried it though.

  35. Lloyd 9 July 2009 at 6:43 pm Permalink

    Hi, great tutorial – really clear and you have gone though the process stage by stage but, I’m still stuck.
    I copied the code, saved it into a file called contact.php and changed the email to my own. I then uploaded this file along with the jquery.validate.pack and tested it entering http://www.lexinc.biz/contact.php.

    when I come to that address all I can see is code on a white background, no form to be found!?
    soooo frustrating, i’m obviously doing something daftly wrong and I’m sure its simple…please help!
    the hosting package include php…

    what could be the problem, I would be most grateful for a response! thanks, Lloyd

  36. Raymond Selda 9 July 2009 at 8:23 pm Permalink

    Hi Lloyd,

    That is a weird one. Are you sure you have PHP in your hosting package? Try to make sure by creating a new PHP file (whatever filename you want) and put:


    <?php phpinfo(); ?>

    It should output the information in your PHP. Can’t think of anything else why this isn’t working for you.

  37. Lloyd 10 July 2009 at 4:53 pm Permalink

    Hi Raymond,
    I found out that the hosting package didnt support PHP!! argh!
    Just one other thing, the form looks different between firefox and IE….In firefox if you dont enter the required information it comes up under the field box saying “information required” whereas in IE, it comes up with the informaiton at the top of the form “Please check if you’ve filled all the fields with valid information…etc”

    Is there are reason that it is different?

    Thanks for your help, I really appreciate it – if you need to show people working examples please refer them to http://www.lexinc.biz if you need.

    Lloyd

  38. Raymond Selda 10 July 2009 at 10:23 pm Permalink

    Hi Lloyd,

    Good thing you figured that one out. Your site’s contact form is looking nice. I believe it’s the plugin’s feature that’s causing that behavior in IE6. It’s nice because it has an extra support for IE6. Looks okay in IE7 and 8.

  39. Coffee 11 July 2009 at 5:59 am Permalink

    Hi Raymond,

    I want to change the request field text: “This field is required.”, I already visit:
    http://docs.jquery.com/Plugins/Validation/validate#options
    but even I dont know how to fix that problem.

  40. Raymond Selda 11 July 2009 at 10:01 am Permalink

    Hi Coffee,

    I’m glad you already visited the documentation page. Just do and follow the example code. Nothing will really happen if you just stare at it. ;) Good luck and please let me know if you’re still having problems.

  41. Anderson 11 July 2009 at 1:48 pm Permalink

    Hello I tried 5 different forms and i get a error either

    Warning: mail() [function.mail]: SMTP server response: 554 The message was rejected because it contains prohibited virus or spam content in D:\———–form.php on line 19
    or
    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\———-contact.php on line 45

    this form gave me 451

    i added the ———- but i don’t think its the code.Ive did some reading and SMTP come up also im with Godaddy.

  42. Coffee 11 July 2009 at 6:11 pm Permalink

    Hi Raymond,

    first thanks for your request and for this nice script.

    I dont only stare at the page, I try a many times a many things. But I just dont understood how and where to put the code which is wirtten there:

    $(“.selector”).validate({
    rules: {
    name: “required”,
    email: {
    required: true,
    email: true
    }
    },
    messages: {
    name: “Please specify your name”,
    email: {
    required: “We need your email address to contact you”,
    email: “Your email address must be in the format of name@domain.com
    }
    }
    })

  43. Raymond Selda 11 July 2009 at 7:59 pm Permalink

    Hi Coffee,

    Nice to know you’re trying things out. I also tried to work this one out and I have to admit that it’s kinda tricky. After trying a few things out, I finally got it to work. Just change your code (head section) to:


    <script type="text/javascript">
    $(document).ready(function(){
    $("#contactform").validate({
    messages: {
    contactname: "Please specify your name",
    email: {
    required: "We need your email address to contact you",
    email: "Your email address must be in the format of name@domain.com"
    },
    subject: "Please enter a subject",
    message: "Please enter your message"
    }
    })
    });
    </script>

    Try it and please let me know your results. Thanks and good luck.

  44. Coffee 11 July 2009 at 10:08 pm Permalink

    Hi Raymond,

    what shall I say, you put the sugar in my coffee, now it taste good. I thank you very much, it works.

    There is just one little more thing for betterment, after the mail was sent, it is possible to refresh the page which send with every reload the mail again.
    When the mail was sent, how I can redirect to another page after a few seconds?

  45. Raymond Selda 11 July 2009 at 10:20 pm Permalink

    Good to hear it’s working Coffee. As for the redirection, one way to accomplish this is you can put a header redirect function header("Location:http://www.domain.com/page.php") after the conditional statement that checks whether the email is sent inside the body. Try that one. Good luck.

  46. stefan lesik 17 July 2009 at 6:31 am Permalink

    this script is great and works well on my server, however, I get the following error message when I upload it to the clients server. Could it be because their host doesnt support php? cant think of another reason???
    Notice: Undefined variable: subject in \\NAS42ENT\domains\s\s…….

  47. liz 18 July 2009 at 8:09 am Permalink

    Hi there,

    First off, what a fantastic tutorial. Very clear and easy to follow.

    I’ve uploaded all of my files and everything looks/works great. I just tried to submit a form in IE8 and it didn’t work. The fields cleared, but neither the success/failure messages appeared and no e-mail came through. I’ve submitted the form successfully in both Firefox and Chrome so I’m not sure what the problem could be.

    Thanks again for an awesome tutorial and any feedback you can provide.

    l.

  48. Raymond Selda 18 July 2009 at 10:16 am Permalink

    Hi Liz,

    Thanks for the comment. Try to copy and paste the code from this tutorial. I would recommend you write it manually to learn more efficiently but you have to check carefully. Check everything. I’ve tested the form in IE8 and it’s working okay (I received the message and email). Good luck. I know you can pull it off.

  49. liz 18 July 2009 at 10:11 pm Permalink

    Hi Raymond,

    Thanks for the quick reply. After copying the final code at the end of the tutorial, I tried it in iE8 and it worked. I had a look and I figured out what the problem was. I had created a submit graphic to replace the gray box in order to match the look of the page. I was using this:

    IE8 didn’t like that very much.

  50. xdin 21 July 2009 at 1:29 am Permalink

    Hi Raymond,

    First of all, I would like to thank you for this great tutorial!

    Second, I have this problem with cyrillic text. When I tested the form by typing in cyrillic text, which is important for me, and sent the message, I received complete nonsense like: привет instead of the cyrillic text. Can you help me?

  51. user_711 24 July 2009 at 4:09 pm Permalink

    Awsome form! Will this ever work in ie6?

    Thanks!

  52. user_711 24 July 2009 at 4:11 pm Permalink

    …to follow on my comment – in ie6, I can get everything to load ok, but you are not able to click and type on any text field

  53. Robin 24 July 2009 at 9:50 pm Permalink

    Hey,

    Great script thank you. Only problem is that when viewing the demo and trying it on my own site i get a page error in IE6? You know the little yellow icon that is next to ‘Done’ in the status bar..any ideas what is causing that?

  54. Raymond Selda 24 July 2009 at 10:33 pm Permalink

    I’m really sorry guys but right now I don’t have enough time to wrestle with IE6. Hope you understand.

  55. user_711 25 July 2009 at 11:03 am Permalink

    No prob Raymond – just wanted to make sure it wasn’t something I was doing – checked more into it and it seems other forms that are out there and built w/ the jquery validation don’t play nice w/ ie6 either – just going to use a simple redirect for those users to a more basic page – nice tut! very useful!

    Thanks again!

  56. Seyfertt 27 July 2009 at 4:59 am Permalink

    Very Good!

  57. Keay 1 August 2009 at 12:53 am Permalink

    I don’t know if I am lost or just have a brain-freeze but here it goes. In order to have the field validated you said to put in “class=”required”. But then how would you be able to style the required message?? For example if you style the message to RED font then that also means whatever you type in the input box is also RED….

  58. Raymond Selda 1 August 2009 at 1:10 am Permalink

    Hi Keay,

    When you send the form with errors, the plugin will insert a label (This field is required) with class in the code. You can now style that label using CSS. You don’t have really to put any CSS for the ‘required’ class because it’s needed by the plugin. Hope that answers your question. Thanks for asking.

  59. Keay 1 August 2009 at 1:14 am Permalink

    Thanks for the quick reply. What I mean is I want to style the required field label to RED for example. So when the message comes out, it is visible. But since the class=”required” is inside the input tag, it makes the text inputted RED also….Hope that is more clear on what I am trying to do..

  60. Raymond Selda 1 August 2009 at 1:25 am Permalink

    Hi Keay,

    Thanks also for the quick reply. hehehe. You will give the red styling to label.error and not to the input tag. If you want to style the input tag you can do so by ‘class=”required yourclass” />’ and then style “yourclass”. Again, if you want to style the ‘field is required’ messages, you can do so by applying CSS to label.error instead. Hope that helps Keay (having troubles pronouncing your name. hehehe).

  61. Keay 1 August 2009 at 1:45 am Permalink

    Great, label.error was what I was looking for….Thanks for the great tutorial (especially having it all in one file)

  62. Keay 1 August 2009 at 2:12 am Permalink

    One more question. How could you go about validating an input field but not have it required? For example the contact number field I want to make it optional but if the user types the number in, I want to make sure it is sanitized but also validated to make sure it’s all numbers..etc…

    • Raymond Selda 1 August 2009 at 2:25 am Permalink

      You can write a custom PHP code or a Javascript code to filter out the field. I’m going to sleep now. hahaha.

  63. J 9 August 2009 at 4:54 pm Permalink

    This was the best mate, thank you so much for providing such handy code and presented with best manner.

    regards,

  64. wormeyman 13 August 2009 at 6:22 am Permalink

    I followed your tutorial but it causes my pages to take a LONG time to load and it spits out 2 javascript errors in firebug even in your own example page. http://raymondselda.com/demo/php-contact-form/contact.php do you know what those errors mean?

  65. Rapheal 14 August 2009 at 6:57 am Permalink

    hey i used the code here verbatim and it sends me the email from the form, however with just the text result, the actual form input data is not there. its like the variables are not translating over what they really stand for. any help would be great

  66. Tom 15 August 2009 at 6:17 am Permalink

    Great form! Any way have it set the ‘reply-to’ address as the sender of the results so it would be easier to reply to the person that filled out the form?

  67. Jorge 15 August 2009 at 11:11 pm Permalink

    Muy buen tutorial..gracias amigo…

  68. Alex 18 August 2009 at 9:16 am Permalink

    Ray, Thanks so much for all the help you have provided as well as the awesome contact form.

    Is anyone having trouble with using this on a GoDaddy Server? I can get this to work on a friend’s server, but for some reason, when I transfer everything over and test it out – I get an error:
    “Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\3320592\html\contact3.php on line 45″

    Line 45 is the mail function.

    I ran my server’s php info and it reads that I have PHP Version 5.2.5

    I also created a blank php page and tested the mail function with something like this:

    Success – I got an email.

    I can’t figure this out on my own and any support would be greatly appreciated from me and fellow GoDaddy users.

  69. Alex 19 August 2009 at 12:53 am Permalink

    I contacted GoDaddy about the problem. They wern’t much help but recommended the following:
    1. specify an outgoing mail server
    2. specify the relay hosting server. They said relay-hosting.secureserver.net with port 25 works
    3. specify SMTP settings

    I’m very new to php and contact forms – any help would be appreciated. Thanks!

  70. Kidwell 25 August 2009 at 12:25 am Permalink

    Hello, thankyou for this tutorial,

    I have one quick question.

    i need to use this as part of a joomla project i am currently working on.

    I dont feel it is safe to include PHP inside of an article itself.

    Is there a way of having all the php, css and html in seperate files?

    Thank you for any help you can offer!

    Kind regards,

    Tom Kiddle.

    • Raymond Selda 25 August 2009 at 12:36 am Permalink

      Hi Tom,

      Yeah. I think I wouldn’t include the script inside WordPress articles either. It all depends on the platform that you use. I don’t have any experience with Joomla so I can’t be sure how you would approach it. But I have to say that it can be done using separate files. Good luck with that.

  71. hari ghimire 25 August 2009 at 5:58 am Permalink

    Hi, nice great stuff!
    but can I call this jQuery and PHP form validation from external file, like say not embedding all the codes in contact.php because I don’t want my email address to be displayed to everyone?

  72. BlackBird 28 August 2009 at 3:20 am Permalink

    Hi, excelent tutorial.
    I wonder if its possible to use the form inside a shtml, because I need to use includes for the header, menue, and footer and in php documents I can’t.

    Thanks!

  73. Joel 1 September 2009 at 10:19 am Permalink

    Hi thanks for the tutorial,

    Im having a problem, the form works perfectly by itself but when i place it inside a div it doesnt run the php script?
    any suggestions,

    Thanks

  74. Sarah 3 September 2009 at 2:56 am Permalink

    Thanks so much for this!!!!!

  75. Dajuan 8 September 2009 at 9:07 pm Permalink

    Raymond, I learn best from sample code and your tutorial has been the best.

  76. Richard 12 September 2009 at 2:48 am Permalink

    It is best code of jQuery, but we use jQuery in different-2 in our website i think we have to change coding ..

  77. Kevin 15 September 2009 at 2:55 am Permalink

    Is there a way to change the location of the error text?

  78. Lauren 15 September 2009 at 5:23 am Permalink

    Ray, THANK YOU SOOOO MUCH for taking the time and energy to share your wisdom, your tutorial is EXCELLENT!!!

    I know you are bombarded by requests, but if you have an easy answer would you please help me.

    what I am baffled by is-
    when someone fills out my contact form on my site it sends me an email (duh) and then when I hit reply…it is (supposed to be) programmed to reply to THEIR EMAIL ADDRESS. which it always did before.

    now either I accidentally changed the code, which I have checked thoroughly and appears to be correct:

    {
    $additionalHeaders .= “\r\nReply-To: $email”;
    }

    OR MY GOOGLE ACCOUNT HAS LOST IT’S MIND!

    because here is EXACTLY what the google email header says when I get an email from my contact form, which is correct:

    from My Site
    reply-to person_who_filled_out_form@yahoo.com
    to myname@mysite.com
    dateSun, Sep 13, 2009 at 2:06 PM
    subject TESTING RESPONSE

    but when I hit reply IT SHOULD go to person_who_filled_out_form@yahoo.com WHICH IS WHAT IT SAYS!!! but instead it goes to me at: myname@mysite.com

    why would it suddenly not work…even when it says it will do what I am wanting??

    thank YOU…THANK YOU THANK YOU THANK YOU!!!

    Lauren

    if you want to check out the exact web page SOURCE it is:
    laurenrick DOT net/contact_me.php

  79. nigel 17 September 2009 at 8:35 pm Permalink

    amazing tutorial,thanks

  80. Gerardo PISD 24 September 2009 at 10:48 pm Permalink

    Hi, I have a problem with the script….

    What if I need to add fields???
    can I use this?:

    <?php
    //If the form is submitted
    if(isset($_POST['submit'])) {

    $date1 = $_POST['date1'];
    $fiebre = $_POST['fiebre'];

    those are my values!!! as checkboxes…. but I never receive the mail… why??? How can I do this possible?? I need to add 4 checkbox and 1 date field!!!! I'm using this..

    Fecha:
    <input type="text" name="date1" id="date1" value="” class=”required” disabled=”disabled” readonly=”readonly” />

    PLEASE SOME HELP….
    oo.. and Sorry my english.. I’m from Mexico.

  81. mimi 28 September 2009 at 3:37 am Permalink

    Hi Raymond,

    Thanks for the great tutorial.
    After user submits the form, how do you send them to a new page rather than view the same page.
    Like, i want to send them to a Thank You page.

    thanks

  82. mimi 29 September 2009 at 4:48 am Permalink

    Hi!

    I used the header redirect function header(“Location:http://www.domain.com/page.php“) after the conditional if statement, but I received an error. Perhaps I wrote it incorrectly.

    this is what I put.

    Help!
    thanks
    Mimi

  83. Peter 1 October 2009 at 10:49 pm Permalink

    Works perfectly. Thank you for this small and simple to implent contact form. The many comments with your reply also helped a lot.

  84. Gopal Raju 5 October 2009 at 12:22 am Permalink

    This will come handy!

  85. simon 7 October 2009 at 6:00 am Permalink

    Hi, trying to implement this form but when I submit it always shows the message “Please check if you’ve filled all the fields with valid information. Thank you.” rather than the ajax validation messages….?

    any thoughts please?

    many thanks

  86. Corey 8 October 2009 at 12:27 am Permalink

    Exactly what I’ve been looking for!

    You also pulled off the minimalist design of your website superbly too.

    Thanks!

    • Raymond Selda 8 October 2009 at 9:29 pm Permalink

      Hi Corey. Glad the contact form was helpful. Thanks for the kind words.

  87. joenebula 8 October 2009 at 11:06 pm Permalink

    Hi Great tutorial. Very easy to understand. But I have a question.
    If you have two forms on a page how can you include them both. Im not sure how to add this function. I think it needs to go in the head before the DOC TYPE code. Really really new to all this.

    Thanks in advance :o)

  88. Ashish Tupkar 10 October 2009 at 10:32 pm Permalink

    R/Sir/Madam
    Sir, myself Ashish working as a PHP programmer in greycells. I want to learn jQuery as soon as possible and also sir I have to make such a function that , ” to allow website visitors to search for phrases and words and find pages with content that matches” in jquery and it should run without need of google or any searchengine and sir my website generates pages from database, Sir if its possible then please send me the script as early as possible

    Thanks You

  89. Chico 15 October 2009 at 5:51 pm Permalink

    Nice Tutorial! Did somebody fixed the problem with IE6 ?

  90. dana 16 October 2009 at 8:32 am Permalink

    Thanks the form works great, and the style is simple but sweet.

    I have one question about the usability of this form. If invalid data is entered a message displays and all information entered in the the form is cleared.

    I often fill out a form and forget to add the “@domain.com” in my email. At which point, while using this form I would loose my beautifully composed message.

    What are your thoughts about the usability? I hope my form isn’t the only one behaving in this manner.

  91. dana 16 October 2009 at 8:50 am Permalink

    Okay I tested your demo form and I see the screen shot where it says “this field is required” — I also see the tip about reading the documentation. Sorry for the hasty reply….and I think I understand which part I skipped.

  92. Marc 16 October 2009 at 11:32 am Permalink

    Hey, great tutorial! Got this thing up and running with relative ease.

    Question though, my website is setup using jquery to show/hide divs based on the page you’re viewing. Basically, if you’re at index.php#home, you’re on the home page. index.php#contact, you’re on the contact page.

    The problem I have is, whenever the form is submitted, it reloads index.php rather than index.php#contact. How can I direct the contact form to #contact?

    Thanks!

  93. Richard Sweeney 17 October 2009 at 5:59 pm Permalink

    Many, many thanks for such a useful and readable tutorial! It’s just what I was looking for.

    I have a question regarding possible spam issues with the form. I’ve placed the actual PHP submit script in a folder on my server and linked to it with a require_once statement. It works great! I am however a little worried about the possible spam implications of the script (if any). I don’t know enough about how it works to say one way or the other!

    I’m probably being very paranoid, but any advice in this regard would be most welcome.

    Again, many thanks for taking time to write the tutorial and for sharing the code!

  94. Trevor Gerring 20 October 2009 at 6:36 am Permalink

    I have everything worked perfectly, but was wondering how to redirect to an anchor within the same page. I am using jquery sliders to direct the user around the page. When I click submit it just reverts back to the initial area when the page is first loaded, not the area where the contact form is. You can view the problem at http://www.unkemptbeard.com

    Thanks for the help and awesome tutorial

  95. Jonas 22 October 2009 at 6:09 pm Permalink

    works great!
    Thank you..
    i have added it into my wordpress installation within 10 minutes.

    good work.
    im going to recommend it to my friends.

  96. Matt Sturt 23 October 2009 at 7:15 pm Permalink

    Hi,

    How do I change the colour of “This field is required” so it stands out. I wnat to keep everything black and have the warning message red.

    Thanks for your help

  97. Matt Sturt 23 October 2009 at 7:28 pm Permalink

    Sorry you’ve already answered my question. All you have to do is add the css tag – label.error
    Thanks for sharing.

  98. Alek 6 November 2009 at 12:40 am Permalink

    Great Tutorial!

  99. dariodn 7 November 2009 at 5:51 pm Permalink

    using gmail I cannot read the message. $Comments go in “subject” line of gmail?
    how can I resolve? tnx

  100. Marc-André Méanrd 10 November 2009 at 12:01 am Permalink

    Here is a question : Why do you validate in PHP while there is NO possibilites that error field can go through

    if(trim($_POST['subject']) == ”) {
    $hasError = true;
    }

    with the require, the empty field cannot be post

    Is there anything i dont understand ?

  101. Brett Shegogue 18 November 2009 at 10:47 am Permalink

    First off. Just wanted to say how much I really appreciate you sharing this. It is an amazing tutorial and was easy to follow.

    One major issue I had was that after submitting the form, the form fields were still there! I just added a simple Else statement and after submission only the response appears. I have pasted the code below. Second, I noticed that if I use test@test.com as the submitters email it will go through, but I won’t get the email (in my inbox, or in my spam). Does this deal with the validation javascript?


    <?php if(isset($emailSent) && $emailSent == true) { //If email is sent
    echo "Email Successfully Sent!
    Thank you for using my contact form! Your email was successfully sent and I will be in touch with you soon.
    ";
    }
    else{

    echo "

    Name:

    Email:

    Subject:

    Message:

    ";
    } ?>

  102. Brett Shegogue 18 November 2009 at 10:48 am Permalink

    oops, it looks like the code didn’t paste correctly. I’d appreciate it if you could fix. Thanks!

  103. Fran 18 November 2009 at 11:33 am Permalink

    thank you so much! :)

  104. Fran 19 November 2009 at 9:13 am Permalink

    Marc-André Méanrd, I have the same issue in sending empty fields without validate, what I did was:

    1º add new field:

    Teléfono:

    2º if the empty is empty I insert a message:
    if(trim($_POST['telefono']) == ”) {
    $telefono = ‘No se introdujo telefono.’;
    } else {
    $telefono = trim($_POST['telefono']);
    }
    3º add the new fields in the $body:
    $body = “Nombre: $name \n\nEmail: $email \n\nTelefono: $telefono \n\nDomicilio: $domicilio \n\nCodigo Postal: $codigo \n\nCiudad: $ciudad\n\nComments:\n $comments”;

    greets
    Fran

  105. jazzi 20 November 2009 at 4:07 pm Permalink

    //a question about the mail{}

    Hi great work. here is a question about //// mail($emailTo, $subject, $body, $headers);

    this mail{ } needs our host support smtp, unfortunately my host doesn’t support smtp, Can I use a third smtp service?

    if yes, how to write the php?

    thanks.
    jazzi

  106. Eva 8 December 2009 at 6:16 am Permalink

    Hi I really like your form. I have a stupid question. I have a four page website and I would like to use the form on every page (for quotes I am a designer), is this the right type of form or is this gonna mess up my whole site?
    Thank you for your help

    • Raymond Selda 8 December 2009 at 10:32 am Permalink

      Actually that’s a very good question. I think you can use that form in any page and it won’t mess up anything. That would actually be a nice experiment for you. Maybe you could try putting the form on your sidebar. Try it and good luck.

  107. Henry 10 December 2009 at 2:34 am Permalink

    Just wanted to thank you for this awesome and simple to follow tutorial. One thing I would suggest is getting a plugin so that the syntax is more understandable.

  108. Brice 14 December 2009 at 3:45 pm Permalink

    thank you for this tutorial !

  109. Paul 22 December 2009 at 7:08 pm Permalink

    The only (big) problem with this contact form is that after a successful send, if the page is refreshed it will send the same email again (and again and again…as often as you refresh the page).

    It should have a 3-5 second delay to show the success message, and then reset itself.

    • selimoff 16 February 2011 at 12:40 am Permalink

      First, THANK YOU Raymond, for this amazing code, really great!

      I was reading every comment since 2009, and at last i found my problem.
      Paul have the same problem that i have. I receive the same email every time i refresh the browser.

      any reply for this?

      Thank you again

  110. Radhika 25 December 2009 at 2:33 pm Permalink

    Nice article but not work on IE5,IE6,IE7

  111. Stephen 14 January 2010 at 2:33 pm Permalink

    So my contact.php is up on the webserver, and when I attempt to submit the form info I get this….

    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\5210379\html\contact.php on line 45

    I’m having trouble resolving this……help?!

  112. Eva 15 January 2010 at 5:16 am Permalink

    Hi Raymond,

    I started working on the form. I put it on my first page. It looks great, I have done some css changes and it matches my website. On technical side – all the functions work properly, except for one important thing :-) – it does not send the email. I have tried mac mail, yahoo mail, nothing. The website is not finished yet, so I am testing the PHP page it through MAMP. Could that be the problem or what am I possibly doing wrong? Please help.

    Thank you

  113. Barry 22 January 2010 at 1:25 am Permalink

    Great article! Just wondering… is there a way to display the thank you message using the same jQuery function without reloading the page?

  114. Guille 22 January 2010 at 7:04 am Permalink

    Hi!
    I´ve the same problem as Eva, but on a PC.
    It doesn´t send any mail.
    What could be wrong?

    Thanks a lot, the tutorial is wonderful!!

  115. Eva 24 January 2010 at 8:07 am Permalink

    Guille,

    You need to upload your php file to the server, than the form works perfectly. The problem with MAMP or WAMP is that it will let you test the page and the jquery functions, but the form just doesn’t send out emails from there. Maybe the “pro” version does who knows :-).

    This is a great tutorial and so far only contact form that actually works, but this guy Raymond doesn’t seem to be answering posts anymore, so good luck!

    • Raymond Selda 24 January 2010 at 10:36 am Permalink

      Thanks Eva for taking the time to answer the question. I know that will help many people with their issues with the contact form. Everything is laid out in this form and I don’t plan to update it. If everything doesn’t work for the first time then don’t give up. Look at every line and test everything. Actually I didn’t get this to work the first time and it took me quite a long time to make it really work. Just don’t quit. This is only a basic form and you can take it to the next level if you want to. Honestly it’s been a while since I’ve programmed in PHP. hahaha.

  116. Eva 28 January 2010 at 1:33 am Permalink

    Raymond lives! hahaha, what a surprise, I thought you have abandoned the page.

    Anyway, since I’ve answered a question for you, perhaps you can help me with this issue – I have asked you above whether the form won’t mess up my page. Well it did.
    I have a lightbox 2.04 on one page and the contact form coding knocked off the function, so now it does not work at all – aaaaahhh. I am not skilled enough to fix the javascript code. Any suggestions?

    here is the link to my page: http://colemanecreative.com/portfolio.php

    • Raymond Selda 28 January 2010 at 11:31 am Permalink

      Hi Eva,

      You have a very nice website and I love your work. Believe it or not I’m not really that much skilled in Javascript either. Honestly, I hate JS. hehehe. What you can try is also use jQuery for your lightbox functions just to avoid Prototype/Scriptaculous functions from conflicting with jQuery. Hope this helps and good luck.

  117. Shellez 5 February 2010 at 6:40 am Permalink

    This is awesome! I can’t believe its so easy :) Thanks.

  118. bluantinoo 9 February 2010 at 1:40 am Permalink

    Hi, thanks for the script, pretty quick and handful. I just wanted to say that th functino to validate email format (functino eregi) is now deprecated.

    I solved changing this line:

    } else if (!eregi(“^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$”, trim($_POST['email']))) {

    into this:

    } else if (!preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i”, trim($_POST['email']))) {

    it just work fine.

    Thaks again for the good work

  119. yaseen_adam 22 February 2010 at 4:20 pm Permalink

    thank you for this tutorial but not work on IE5,IE6,IE7

  120. Meble 25 February 2010 at 5:10 pm Permalink

    Very good tutorial :)

  121. Frank 28 February 2010 at 5:36 am Permalink

    I love this – it works great with one problem; it fires off an email (with blank fields, of course) when the page loads. Once the fields are filled out and submit is pressed it works perfectly.

    I think the problem is this:

    When the page loads the first two functions seem to load. The first function will only trigger if there was a Submit, which there isn’t. The second function will actually run because the hasError variable was never initiated and does NOT resolve to ‘true’.

    I don’t know how to fix it though. Any ideas?

    Thanks for all your time and effort.

  122. Pauline 2 March 2010 at 8:36 am Permalink

    Hello,
    I’m a french designer, sorry for my poor english.
    I’m trying to use this contact form, here is a test page : http://www.paulinegirondin.com/contact/contact2.php

    But I dont receive the mails I try to send? (I’m looking for the problem from few hours ago!) Can you help me please?

    Do you know how I can put the “error fields” in french?

  123. Crhystyann 2 March 2010 at 11:00 pm Permalink

    Genial hasta el momento me ha funcionado!
    voy a intentar crear más campos y si me queda bien coloco el link donde lo pude usar
    Muchas Gracias Raymond!

  124. xhino 5 March 2010 at 1:46 am Permalink

    Hi, first awesome tutorial men… thanks to make this things

    Second, im looking for the line that modifies the messages of the validation process, my web site is based on Spanish Language…

    Please i need ur help

  125. matthias 18 March 2010 at 6:42 am Permalink

    Thx! One little thing:

    Name:

    should be

    Name:

    ( Change for=”name” to for=”contactname” in order to activate the input field with a click on the label “Name”) Hope you get what I mean ;)

  126. Rasterfield 18 March 2010 at 1:15 pm Permalink

    Thanks. It works beautifully.

  127. Dan Gold 20 March 2010 at 4:14 am Permalink

    Hey, I love this tutorial and I am about to implement it into a new design. I kept getting my mail in my spam folder in gmail so I changed the $headers line to $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email; – works great now!

  128. Chris 25 March 2010 at 2:59 am Permalink

    Oh my god, a programmer who can actually write a coherent tutorial!

    Thanks Raymond!

  129. builder 25 March 2010 at 8:49 pm Permalink

    Very good tutorial. Everything is clear and clearly explained. Many thanks!

  130. Jessica C. Calzita 27 March 2010 at 5:31 pm Permalink

    just wanna ask..why is that everytime i fill up the form i didn’t received any message to my email..all i want is after fill-up the form…on my yahoo mail “jheyven_05@yahoo.com” will send directly the message that i put it on the form?? how can i do this???

  131. Jostein 7 April 2010 at 4:26 pm Permalink

    Great one! Thank you!

  132. Darko 18 April 2010 at 10:27 pm Permalink

    Great tutorial, it works great, but I have one question…
    Is it possible to set up custom error messages like PLEASE TYPE YOUR NAME instead THIS FIELD IS REQUIRED ???

    Thanks

  133. Hernan Pesce 20 April 2010 at 5:47 pm Permalink

    Hello Raymond. My question is: I’ve test the form on a Linux server and the email arrives ok… but I’ve also test on a Windows Server, and the mial doesn’t arrives…. I mean.. the email seems to be sent, but nothing arrives… Any suggestion?

    Thanks and regards

  134. Faisal Basra 20 April 2010 at 6:38 pm Permalink

    This is great work..

    Just need to know, how can we give custom error message for particular text field? Say, a textfield is username and I want to show message “username can’t be empty” something like this.

  135. Helio Pinto 22 April 2010 at 6:40 pm Permalink

    Great Staff,

    Thanks for sharing

  136. Andy Jordan 30 April 2010 at 12:16 pm Permalink

    Firstly.. thank you so much, I really appreciate the effort put into making this tutorial so easy to understand.. It is exactly what I wanted :). I have got the script working perfectly but I have a query. Is there a way to display the thank you message ( or the error message) in a pop up style dialogue box, like within a JQUERY UI style box instead of displaying it in the default position above the form. If you see http://twitaflick.com/avatar and click contact you will see why I require this. Once a user hits submit, the page is reloaded and no thank you message is displayed unless they were to press contact again, as the contact form is within a slide panel located at the top of the page. If a pop up message was to appear it would be cool and solve a problem :)

  137. Will 5 May 2010 at 3:37 am Permalink

    thanks for the wonderful form, works like a charm! I do have a question though. I wanted to add a couple of fields that aren’t required. I really don’t know php and only just found out you can’t lookup php code by looking in the source :-)

    I was reading through the comments but couldn’t find the solution. Could someone help me out with the code?

    Thanks in advance!
    Will

  138. Andreas Burghart 6 May 2010 at 5:55 am Permalink

    I also had the problem, that no mails came in. Perhaps you can solve the problem by changing the settings in the administration of your provider. I had to define a mail address as default first and then it worked.

    P.S.: I`m from Germany, so please excuse my bad english.

  139. Andreas Burghart 6 May 2010 at 6:01 am Permalink

    I also had the problem that no mails arrived. I could solve it by changing the settings in the administration area of my provider (hosteurope): I had to define a mail address first as default.

    P.S. Excuse my bad english. I`m from Germany…

  140. dave P. 10 May 2010 at 11:36 am Permalink

    Josh form webadminblog.com has an article describing an XSS exploit vulnerability when using as the form action

    http://www.webadminblog.com/index.php/2010/02/23/a-xss-vulnerability-in-almost-every-php-form-ive-ever-written/

  141. Jessie Daryl Cacafranca 10 May 2010 at 1:44 pm Permalink

    how to add smtp authentication?

  142. Kravas Pārvadājumi 17 May 2010 at 8:06 pm Permalink

    Did work for me, thanks!

  143. Swagat 21 May 2010 at 7:11 pm Permalink

    Hey can i send the contact form data to 2 email id.s? if so, how?? Please reply, URGENT

  144. Damien Collis 25 May 2010 at 5:30 am Permalink

    Great tutorial, many thanks!

    Just wondering if its possible to change the background colour of the ‘Send Message’ Submit button?

    Many thanks,

    Damien :o)

  145. Julian 29 May 2010 at 6:00 pm Permalink

    Would use $_SERVER['SCRIPT_NAME']; on form.

    Thanks.

  146. Shaddy 1 June 2010 at 7:43 pm Permalink

    This was the best tutorial i found on the topic – simple, well structured and explanatory, thank you so much. My current assignment got a lot easier.

  147. Suziy 3 June 2010 at 1:45 am Permalink

    Its an elegant contact created form using jquery

  148. Coder 5 June 2010 at 3:47 am Permalink

    Hi there, thanks for the tutorial.
    However, have you check the finished code?

    It has errors:
    ‘ . “\r\n” . ‘Reply-To: ‘ . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?>

    That sits on top of the form when finished? Missing some code in the top part of the PHP code. What would you recommend?

  149. matvespa 6 June 2010 at 8:14 am Permalink

    Hi. Great Tutorial!
    Just want to ask, how do i edit the error message?
    For example “This field is required.” to “Please enter username”.

  150. James 9 June 2010 at 6:10 am Permalink

    I was wondering how, instead of the email being from “My Email” if you could make it from the email entered in the form. I tried putting a ‘$email’ after $headers = ‘From: but it just made the text ‘$email’. I also tried copying the ‘ . “\r\n” . ‘Reply-To: ‘ . $email; and changing it to $emailFrom but I got an error. I’m sure this is a simple thing to do, I’m bad at php. I apologize if this has been addressed already. Thanks for the tutorial!

  151. Jeff Doan 9 June 2010 at 11:49 pm Permalink

    How do I CC / BCC someone?

    Awesome tutorial BTW.

    Thanks!

  152. dan 10 June 2010 at 9:09 pm Permalink

    Why after i press the send button the text with the thanks message doesn’t appear?
    Can anyone help me?

    This is the code:

    <?php
    //apas pe trimite

    if(isset($_POST['submit'])) {

    //nume este gol?
    if(trim($_POST['nume']) == '') {
    $hasError = true;
    } else {
    $nume = trim($_POST['nume']);
    }

    //prenume gol
    if(trim($_POST['prenume']) == '') {
    $hasError = true;
    } else {
    $prenume = trim($_POST['prenume']);
    }

    //telefon gol
    if(trim($_POST['tel']) == '') {
    $hasError = true;
    } else {
    $tel = trim($_POST['tel']);
    }

    //adresa mail valida
    if(trim($_POST['email']) == '') {
    $hasError = true;
    } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
    $hasError = true;
    } else {
    $email = trim($_POST['email']);
    }

    //comnetarii
    if(trim($_POST['message']) == '') {
    $hasError = true;
    } else {
    if(function_exists('stripslashes')) {
    $comments = stripslashes(trim($_POST['message']));
    } else {
    $comments = trim($_POST['message']);
    }
    }

    //formular corect trimite mail
    if(!isset($hasError)) {

    $sendTo = "kondrei@gmail.com"; //adresa la care vrei sa se trimita mesajul
    $subject = "Mesaj de pe site-ul WoodArt";
    $headers = "From: " . $_POST["nume"] . " " . $_POST['prenume'] . " \r\n”;
    $headers .= “Reply-To: ” . $_POST["mail"] . “\r\n”;
    $headers .= “Return-path: ” . $_POST["mail"];
    $message = ”;
    $message = ” Nume: “.$_POST['nume'].”\n Prenume: “.$_POST['prenume'].”\n Telefon: “.$_POST['tel'].”\n E-mail: “.$_POST['email'].”\n Mesaj: “.$_POST['message'];
    mail($sendTo, $subject, $message, $headers);
    }
    }
    ?>

    WoodArt – Contact

    $(document).ready(function(){
    $(“#contactform”).validate();
    });

    label.error {
    font-weight: bold;
    color: #742c30;
    }

    Home
    Produse
    Tehnologie
    Garanţii
    Recomandări
    Contact
    ENGLISH

    Please check if you’ve filled all the fields with valid information. Thank you.

    Vă mulţumim pentru mesaj!
    Un coleg vă va răspunde la solicitare în cel mai scurt timp posibil.

    Contacteazã-ne!
     

    Showroom

    BucureÅŸti, Str. EpureÅŸti, Nr. 11
    Tel./Fax 021.668.47.26, 021.668.47.30

    Producţie
    FloreÅŸti, Jud. Cluj, Str. prof. Ioan Rusu, Nr. 3
    Tel. 0264.265.530, Fax 0264.265.150

     

    Solicitare ofertă de preţ
    <form method="post" action="” id=”contactform”>

    Numele tău:

    Prenumele tău:

    Telefon:

    Adresa de e-mail:

    Message:

    * Toate câmpurile sunt obligatorii

    Copyright, 2010 SC General Comexim SRL  • 
    Developed by MediaOne
     •  Valid
    XHTML
     •  Valid
    CSS

  153. jon izeta 14 June 2010 at 6:22 pm Permalink

    Great form and great tutorial!! Thanks a lot!

  154. Justin Gray 15 June 2010 at 9:29 am Permalink

    Once the form is e-mailed i would like it to be replaced with the thank you text. Can anyone help me with the code to do this?

  155. wpdreamdeveloper 21 June 2010 at 10:17 pm Permalink

    Great tutorial..It saves my time. Big thanks to Raymond :)

  156. Jason 23 June 2010 at 12:59 pm Permalink

    I have got right to the end of this tutorial. Then when I put the PHP above the Doctype and previewed it in browser.

    The form did not display at all only the PHP code I pasted in.

    It looks just like yours I’m not sure whats going on.

  157. remote php developer 23 June 2010 at 8:42 pm Permalink

    Thanks Raymond Selda you done a great work..
    this script is using to learn something about you.

    once again thanks to Raymond Selda..

    Thanks a lot..!

  158. Vinnie 25 June 2010 at 12:23 pm Permalink

    Hi guys, good job really usefull and easy to costumize thanks for share it.
    matvespa try in jquery.validate.pack.js looking for the words in the example of message error.

    dan Bad sintaxis mate just check the code.
    Justin Gray is very easy just try to understand what Raymond is doing.
    The code is fully commented if you try and you get some is better than just ask :).

    Good luck!

  159. wynajem 27 June 2010 at 9:47 pm Permalink

    Nice tutorial ;)

  160. Justin 28 June 2010 at 12:57 pm Permalink

    I’ve tried looking in the folder ( jquery.validate.pack.js ), but it’s all keywords! I know there’s a easy method for that but I did grasp the coding part of it yet..

    Look at the source of this site, you see that they changed the error description
    http://jquery.bassistance.de/validate/demo/

    Anyone can bring some methods on how to achieve this ?

    thanks.

  161. Justin 28 June 2010 at 11:43 pm Permalink

    I got it working with my own error comments. I also tried by erasing the javascript and it gives me the simple php error, so it works if someone dosen’t have the javascript enable.

    Now the form is up to my expectation but I would’nt of been able without this script. Thanks again.

    If someone needs help setting up their own error comments, I’ll be willing to help :)

    Justin.

    • Raymond Selda 30 June 2010 at 11:02 pm Permalink

      @Justin: Great job and thank you so much for lending a helping hand. Hope you get the option field. :)

      @Ty Hatch: Thanks for the update

  162. Ty Hatch 29 June 2010 at 2:36 pm Permalink

    Just discovered that eregi is deprecated in php 5.3+. Found that stristr worked for me.

  163. Justin 30 June 2010 at 2:24 am Permalink

    hmm, I can’t seem to put an optional field! The simplest thing, haha!

  164. sarah 2 July 2010 at 12:01 am Permalink

    hi,

    I’m trying to modify the error message but didn’t know how to do it.

    Instead of This is a required field” I need it to change something like… “Name of the field” missing

    how can I place the Label of the field in the error message?

    Thank you, by the way this is a great tutorial :)

  165. gavin 2 July 2010 at 5:26 am Permalink

    Has anyone successfully moved the errorElement? I have the labels and input fields on separate lines and I would like to have the errors appear next to the labels.

    I also figured out how to change the errors from being a label to a span, but cannot figure out how to remove the attributes such as “for” or “generated” without breaking the script.

    Can someone who’s good with jQuery lend me a hand?

  166. Faisal Basra 2 July 2010 at 12:56 pm Permalink

    Thanks Selda for sharing great recipe.

    If anyone can integrate the http://www.google.com/recaptcha, then it would be a great work.

  167. Vicky 5 July 2010 at 8:33 pm Permalink

    Great tutorial, forms have baffled me for so long and finally I think I can make sense of it all!

    I was just wondering, how effective this form would be against spam and also can I make input type=”hidden” or would that not work?

    Thanks

  168. Justin 6 July 2010 at 9:07 pm Permalink

    @sarah

    If you want custom error fields, it would require some tweaking. The following is a short tutorial for those of you who would like to modifiy the error messages. By the way, if you would like to change the style of the error message, it’s all done within your stylesheet with the “label” tag.

    The form itself is like Selda’s except there’s no class for the required, so build your form without them but remember to give your fields unique ID’s.

    Within the header of your contact page, you will need the following links, which are provided by Bassistance :

    Like Selda’s, you will need to put the following above the doctype ( This is an example of the error messages or optional fields, modify to your own requirements. ) :

    <?php
    //If the form is submitted
    if(isset($_POST['submit'])) {

    //Check to make sure that the name field is not empty. This is required because of $hasError = true;
    if(trim($_POST['name']) == '') {
    $hasError = true;
    } else {
    $name = trim($_POST['name']);
    }

    //Check to make sure that the phone field is not empty. Required
    if(trim($_POST['phone']) == '') {
    $hasError = true;
    } else {
    $phone = trim($_POST['phone']);
    }

    //This one is optional, I added the striplashes to take out the / when " or ' is added.
    if(function_exists('stripslashes')) {
    $car = stripslashes(trim($_POST['car']));
    } else {
    $car = trim($_POST['car']);
    }

    //Check to make sure sure that a valid email address is submitted
    if(trim($_POST['email']) == '') {
    $hasError = true;
    } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
    $hasError = true;
    } else {
    $email = trim($_POST['email']);
    }

    //If you don't want the striplashes, simply place the last line of the 2nd else statement.
    if(trim($_POST['message']) == '') {
    $hasError = true;
    } else {
    if(function_exists('stripslashes')) {
    $message = stripslashes(trim($_POST['message']));
    } else {
    $message = trim($_POST['message']);
    }
    }

    //If there is no error, send the email
    if(!isset($hasError)) {
    $emailTo = 'name@business.com'; //Put your own email address here
    $subject = 'New comment received'; //Put your own subject here
    $body = "Name: $name \n\nEmail: $email \n\nTelephone: $phone \n\nCar: $car \n\nMessage:\n $message";
    $headers = 'From: My Website ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    mail($emailTo, $subject, $body, $headers);
    $emailSent = true;
    }
    }
    ?>

    Next we will place the error message in PHP in case the user has deactived javascript for some reason and we will place the Thank you message that will appear above the form. Both of theses could be placed above your form in contact.php…

    Error message:

    Please check if you’ve filled all the fields with valid information. Thank you.

    Thank you message:

    Email Successfully Sent!
    Thank you for your interest in our site. I will contact you shortly if needed.

    That’s it. Here’s a little help for the css styles, but you can add your own to .error and label:

    label {display:block;float:none;width:auto;}
    .error {color:#ad0000;}

    Hope this will help some of you.

  169. Justin 7 July 2010 at 3:28 am Permalink

    Sorry, forgot to add an important detail!

    Below the scripts add the following to edit your error messages. For the fields that are optional you do not add them here. Don’t forget to change the “#yourformid” to your own id :

    $().ready(function() {
    // validate signup form on keyup and submit
    $(“#yourformid”).validate({
    rules: {
    name: “required”,
    email: {
    required: true,
    email: true
    },
    phone: “required”,
    },
    messages: {
    name: “Please enter your firstname”,
    email: “Please enter a valid email address”,
    phone: “Please enter a phone number”,
    }
    });

    });

  170. Richard 11 July 2010 at 9:58 pm Permalink

    Hi Raymond,

    I am using GoDaddy hosting and once i have submitted the form on their servers, it says it sends but i receive no email at all.
    Plus at the top of the screen, i receive this error message:-

    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\5………\html\contact.php on line 45

    Line 45 appears to be – mail($emailTo, $subject, $body, $headers);

    Are you able to be of any assistance? Thank you.

    Regards,

    Richard

  171. Jawahar 12 July 2010 at 2:02 am Permalink

    Great tutorial!
    But the error message and ‘Thank you’ message doesn’t appear! :-(

  172. Henrik 12 July 2010 at 3:50 pm Permalink

    @Jason, you cannot preview php-code in the browser, it is a server-side script and has to be compiled by a server which has php installed. So you need to upload the file to a web-server with php and then type in the address in the browser to that file to see it rendered as it should. Another way you can do it is to install a wamp (windows) or mamp (mac), a package with web server, php and mysql and then you can test it on your own computer.

    Good luck!

  173. uk 14 July 2010 at 2:20 pm Permalink

    This in your tutorial is the most important sentence: “I highly suggest that you don’t rely on Javascript alone for validating form inputs. Aside from validating inputs, PHP will also be responsible for sending out the email in case no errors were found.”

    It´s a matter of security to validate in two steps. Javascript will be executed on the clients machine and it is not secure to let the user validate the data you need maybe for sending an e-mail. A client e.g. can build a own little page without validation and send you some shit just as an attack …
    So it must be to have two way validation!

    I tip: Use REST-api for validation. Send the form-data via JS to the api (which is maybe written in PHP) and let it do the tests. Later you can reuse the validation functions in PHP before you send the E-Mail!

    I´ve done a little tutorial with jQuery and CodeIgniter:
    http://www.karrock.de/daf/2009/10/how-to-validate-forms-with-jquery-and-codeigniter/

  174. Carolina 16 July 2010 at 11:35 am Permalink

    Many many thanks for sharing this form ! It was so much help. Finally I got a form working : ) I still need to change the “this field is required” field to spanish but I already read all questions and comments and found your explanation to “Coffee”. Tomorrow I’ll try it and I’m pretty sure it will work since everything you share with us did.

    THANK YOU!

  175. Blaze Pollard 16 July 2010 at 11:12 pm Permalink

    This is a better one. :) http://madebyblaze.com/examples/awesomeform/

  176. Mr M 17 July 2010 at 2:42 pm Permalink

    The whole point of using Ajax is to improve interaction and feedback to users. So please don’t wait to validate forms before the user presses the send button.

  177. cihip 18 July 2010 at 1:03 pm Permalink

    Great tutorial, many thanks!

  178. mbDizajn 21 July 2010 at 2:18 am Permalink

    Thanks for the tutorial. It’s great contact form. That’s what I was looking for!!!!
    I’ve put it on my website. http://www.mbdizajn.com Working great, without any bug…
    Thanks again! Best regards!!!

  179. Daniel 23 July 2010 at 5:34 am Permalink

    I would like for the script to send an auto response to the senders email address. How do I do this please. Please indicate where exactly to put the code. I’ve been trying to add another mail() to the script but it stops the page working…

  180. Phil 31 July 2010 at 11:01 pm Permalink

    @Richard (and anyone else who is on a Windows/IIS server at GoDaddy or anywhere else):
    You will need to change all instances of “\n\n” in the email scripts into “\r\n” due to differences in the way that Linux/Unix servers and Windows servers process line feeds.

    Thanks to Raymond for putting this together – made things quicker and easier for me today.

  181. robert 5 August 2010 at 7:54 am Permalink

    Hi,

    Your jquery contact php code works perfectly without any modifications other than changing the email address for my http://proxylist.co web site.

    Nice job!

  182. Anonymouse 12 August 2010 at 6:39 pm Permalink

    Excellent working form…..i ever seen on the net.
    Its the easiest form.

    Thanks alot – may GOD bless you – dear friend.

  183. sky 13 August 2010 at 1:09 pm Permalink

    oopz.. what race are u?

  184. bill 18 August 2010 at 8:16 am Permalink

    hi

    brilliant tutorial really clear and well documented

    I get the php validate messages ontop of the contact form when I load the page in a browser??

    can this be fixes? surely these messages should only show up when you click send and nothing is added in each input field??

    Thanks in advance for any help

    b

  185. mel 28 August 2010 at 12:32 pm Permalink

    Thanks. Worked great!

    I made a slight adjust to make sure no ugly php errors and warnings where thrown at the top. Instead, if there were errors, they were displayed nicely in the form.

    1) Changed the php.ini config by adding this line to the top of your code….

    ini_set(‘display_errors’, 0);

    2) Then, added error notification in the header’s javascript

    //If there is no error, send the email
    if(!isset($hasError)) {
    $emailTo = ‘email@youremail.com’; //Put your own email address here
    $body = “Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments”;
    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    if (mail($emailTo, $subject, $body, $headers)) {
    $emailSent = true;
    } else {
    $emailSent = false;
    }

    }

    3) Added this line in the html above the form

    Email Was Not Sent!
    If problems persist please contact us and let us know!

  186. mel 28 August 2010 at 12:34 pm Permalink

    err sorry.. my #3 turned into html … let me repost

    3) Put this above the form

    Email Was Not Sent!
    If problems persist please contact us and let us know!

  187. Devendra 28 August 2010 at 8:36 pm Permalink

    Hello, Contact Form is very Nice and well executed, but when i use this i found some error while sending email, it is giving error like this

    Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\wamp\www\Contact_Form\contact1.php on line 45

    and 1 more, i didn’t able to find “This is required”, i have to replace with “User name required”…

    If you will have time then please help me, you can send solution on my email id, i will wait for your response.

    Thanks and Regards

    Devendra Pawar
    devendra.pawar@quadrabiz.co.in

  188. Given 18 September 2010 at 4:56 pm Permalink

    Thanks : ) great tutorial.

  189. keith 18 September 2010 at 10:50 pm Permalink

    thank you! it’s very clear and simple to understand.

  190. Chris van Liere 23 September 2010 at 5:04 am Permalink

    Thanks!

    i dont know if i can post a link but i just wanna show you the result (: (site isnt online yet so yeh,,) http://www.fayadosu.nl/test/avato/contact.php

    @Damien, i wondered the same but i didnt find it yet, maybe u could make your own button? i dont know first time im working with forms (:

  191. Tom 26 September 2010 at 11:10 am Permalink

    How would I change the submit button to transparent?

  192. santosh pandit 1 October 2010 at 5:53 pm Permalink

    good , nice ,helpful

  193. jaz 4 October 2010 at 5:55 am Permalink

    Works great! Thanks!

    Check it out here:

    http://jazsheen.com/contact.php

  194. Paul 4 October 2010 at 4:19 pm Permalink

    Great tutorial. This is perfect for my site. Just one question. How would I go about having the error messages appear above the form fields, and next to the name of the field rather than below the form fields. I managed to absolutely position the ‘label.error’ css value to minus co-ordinates, which does work, but there must be a simpler way to achieve this. Something in the order of the way the html form code is placed. I can’t seem to work it out though.
    Any help with this would be appreciated.

  195. Jennifer Frey 4 October 2010 at 10:42 pm Permalink

    Great tutorial – but hoping to expand the form to include a newsletter signup checkbox. I don’t know how add that so it emails if the the checkbox was selected or not? Any help would be much appreciated – I’ve been trying to figure it out for way too long!

  196. Sherwin 7 October 2010 at 5:36 am Permalink

    I gave this an honest shot. I want to use the form to redirect the user to another page where they can download an ebook while the email sends me their contact information. After some troubleshooting, I finally got the form to submit without error and to redirect to the download page. BUT, the email that’s sent to me is devoid of the required information. This is what I get:

    from xxxxxx@xxxxxx.bluehost.com
    to download@mysite.com
    date Wed, Oct 6, 2010 at 5:26 PM
    subject xxxxxx Download

    First Name:
    \Last Name:

    Email:

    Phone:

    Organisation:

    This is the mailing code I used:

    //If there is no error, send the email
    if(!isset($hasError)) {
    $emailTo = 'download@mysite.com'; //Put your own email address here
    $subject = "xxxxxx Download";
    $body = "First Name: $first_name \n\Last Name: $last_name \n\nEmail: $emailaddress \n\nPhone: $phonenumber \n\nOrganisation:\n $organisation";
    $headers = 'From: My Site ' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    header( "Location: download-xxxxxx.html" ) ;

    Can someone PLEASE point me in a direction I can find out why I’m not receiving the information in the email?

  197. Ashley 10 October 2010 at 7:07 am Permalink

    @Sherwin

    I had this problem but after having a fiddle I found a working solution.

    Simply replace:

    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    With:

    $headers = “From: {$email} “;
    ————————————————————————————-

  198. tushar 14 October 2010 at 2:14 pm Permalink

    how to add multiple email address

  199. Andrea 15 October 2010 at 10:06 pm Permalink

    Hi! very cool!

    is possible insert the php in a external file??

  200. ken 17 October 2010 at 4:41 am Permalink

    Great plug-in! I merged it into wordpress, and also popped it into a thickbox with no problem. Thanks for sharing.

  201. alex 18 October 2010 at 5:45 am Permalink

    ok

  202. Ryan 19 October 2010 at 4:37 am Permalink

    Is there a way to add 2 of these forms to the same page. I want to use for both a simple newsletter signup in the left column that just takes an email address and is on every page. Then I want to use it for a full form on the contact page with many fields. The problem I am having is that when you get to the contact page and it has the newsletter signup in the left column as well, it gives a “false positive” to the newsletter signup if the user fills out the contact form. Any help would be great. Thank you.

  203. Ryan 21 October 2010 at 12:00 am Permalink

    I figured out the above issue, but now running into another issue. I added several new fields and now it is giving me an error saying i have not filled out all the fields. If anyone can help me with figuring out this problem I would appreciated it. I can post the code here if needed but hate to take up too much room in the comments. Thanks.

  204. Vs 21 October 2010 at 11:18 pm Permalink

    Wow this is exactly what i have been looking for .Good job

  205. Luke 22 October 2010 at 6:56 pm Permalink

    Hi,

    Great tutorial but…

    Is there a replacement for the !eregi bit (in the email field validation) because that’s now deprecated in PHP 6??

    Any help would be greatly appreciated!

    Thanks

  206. Julie franck 22 October 2010 at 8:36 pm Permalink

    Hello !

    how to change “This field is required” to put in French.
    Thank you!

    Julie Franck

  207. Rembo 30 October 2010 at 3:17 pm Permalink

    Very nice, lightweight and easy customisable, thnx!

  208. Paul 4 November 2010 at 11:54 pm Permalink

    Thanks very much. Very useful.

  209. Nicolas (ARG) 8 November 2010 at 7:39 am Permalink

    Hi, first, let me thank you for a great job! Really simple to deploy.

    Now i need more help :). I need to show a jquery.message only if the form is valid. I´m stuck here:

    $(document).ready(function() {
    $(“#contactform”).validate();
    $(“#contactform”).submit(function() {
    $().message(“Gracias por su consulta, en breve lo contactaremos para asesorarlo.”);
    return false;

    });
    });

    Any help would be very appreciated.

    You can see it working @ http://www.martrans.com.ar/nuevo/nuevo/es/cargas.php

  210. Marcus 15 November 2010 at 8:44 am Permalink

    I followed this guide stpe by step and implemented it on my contact page on my own website. When you submit the message this message shows up at the top of the screen and no email arrives to my inbox

    “Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\7009516\html\contact.php on line 45″

    Any idea on how to fix this?

  211. Korin 16 November 2010 at 5:21 pm Permalink

    Thanks a lot for the tutorial.
    I’ve one question:
    can we use recaptcha in this form.

    Thanks again.

    Regards

  212. sam tsohonis 20 November 2010 at 1:17 am Permalink

    Hello
    I am struggling to incorporate a redirect via either [php] header(); located after the mail() command, or [javascript] window.location within the $(form).validate(); function.

    I can get the email to send without redirect or I can get it to redirect without sending the email. It looked like someone earlier was able to get it to do both, but it would appear that perhaps a setting in the javascript or in the form declaration was also revised. Does the form action=”” need to change from PHP->self to something else maybe? HELP!!!

  213. sam tsohonis 20 November 2010 at 1:38 am Permalink

    not to be a pest but I am also using jquery to prompt the field values so I don’t need to put labels in them
    for instance:
    $("#middleinit").focus(function () {
    $("#middleinit").val('');
    });
    $("#middleinit").blur(function () {
    if($("#middleinit").val() ==''){
    $("#middleinit").val('Middle Initial');
    }
    });

    This means that the field label is in the field until a user fills it out. if a user clicks on the field the label in it disappears and if they move to another field without entering it fills in the field with the label again.

    The problem I am having is that if the form doesn’t validate it wipes the information a user has entered. I want to know how to access the values of the fields that do validate so I can keep them filled out when the form validation fails.

    thanks again for the form and for the further assistance.

  214. sam tsohonis 20 November 2010 at 2:23 am Permalink

    got the redirect issue fixed- embarrassingly enough, I just had to move the php to the top of the page before the html. Had that happen enough in the past that I shouldn’t have made the mistake again.

    still hoping for some kind of fix to keep valid fields filled out when invalid fields break the submit process. thanks.

  215. ben 23 November 2010 at 10:52 pm Permalink

    Hey! A nice form that works great too – result!

    Can anyone point me in the right direction for setting it up as an html page with the php in an externally referenced file? Is that easy to do or would it be a complete nightmare? The whole php thing is still a bit of a mystery to me…. = )

    Thanks for sharing this great code!

  216. ric 24 November 2010 at 9:20 pm Permalink

    how can i insert an uploader into this form?
    i’ve to upload 4 image on the server and the name of each image must to be sent in the email.

    anyone can help me?

    thankyou

  217. Jack 24 November 2010 at 10:24 pm Permalink

    I tried to use your contact form, however, the problem when I tested was I couldn’t get the email from the sender. Please advise!!! Thanks

  218. Jack 24 November 2010 at 10:44 pm Permalink

    I tried this way but didn’t work neither. Anyone have a better idea? Please adivse!!!

    Simply replace:

    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    With:

    $headers = “From: {$email} “;

  219. Denisse 25 November 2010 at 3:06 am Permalink

    OMG Im so thankful for this ! its perfect and works great, the tutorial its so easy to understand. Just what i needed. THANK YOU SO MUCH FOR THIS !

  220. Tim 8 December 2010 at 1:05 am Permalink

    Thanks! : )

  221. Justin 6 January 2011 at 11:02 am Permalink

    So, how do I implement this into a lightbox? I am building a site but I don’t want a full dedicated page for a contact form. The code works for validation, but I want it to pop up. I see you got it to work, Ken. Can you (or anyone) assist me in placing in a lightbox? I’ve tried to download and follow instructions for prettyPopin, lightbox, etc.. but not sure how to go about it.. Thanks for any help guys!

  222. Nagore 16 January 2011 at 2:41 am Permalink

    Hi,
    first of all thank you for sharing this. I’ve been looking for a solution like this and this is a great tutorial.

    I initially found myself with the same problem that Marcus did.
    ““Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\7009516\html\contact.php on line 45″”

    After a little bit of research I found that if the “from” email is one from your domain this problem disappears. You still get the senders email on the message, so my solution was to create a bespoke email address on my domain for comment sending.

    may not be the most elegant solution but it works.

  223. matko 16 January 2011 at 1:15 pm Permalink

    great tutorial, workink nice, addition to this script

    $headers = ‘MIME-Version: 1.0′ . “\r\n”;
    $headers .= ‘Content-type: text/html; charset=utf-8′ . “\r\n”

    to work with UTF-8 encodes ,

    if(!isset($hasError)) {
    $emailTo = ‘kontakt@gradac-apartments.com’; //Put your own email address here
    $body = “Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments”;
    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;
    $headers = ‘MIME-Version: 1.0′ . “\r\n”;
    $headers .= ‘Content-type: text/html; charset=utf-8′ . “\r\n”;

  224. Miyiura 18 January 2011 at 9:53 am Permalink

    Thanks for this.
    Very useful!

  225. CJ 19 January 2011 at 11:45 am Permalink

    @ luke and those looking to fix the “eregi depreciated” error:

    use preg_match instead

    replace

    else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))

    with

    else if (!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email'])))

    That should fix it all up

  226. Chester Web Design 20 January 2011 at 10:48 pm Permalink

    Works great, thanks for sharing this!

  227. Hernan Pesce 24 January 2011 at 10:36 pm Permalink

    Hi.. very usefull….!!!… one question.. How or where can I traslate tags like “This field is required.” or others??….
    Thanks very much

  228. Suraya Hamdan 25 January 2011 at 6:55 am Permalink

    Got it working very well including integration with recaptcha

    take a look here http://unikl.org/contact/

    Thanks a lot for the tutorial, it really helps! =)

  229. david 25 January 2011 at 5:32 pm Permalink

    Hi, great form, how easy would it be to add a cc so the data is emailed to 2 email addresses.

    thanks

  230. Santiago 27 January 2011 at 12:08 am Permalink

    Hi! I would like to add more fields. How can I do that? I’ve been trying to add a last name field, for example and it doesn’t work properly! I need to put some extra fields for “city”, “job”, “telephone” and few others… Also, if someone knows any way to include a submit field for attach a .pdf or .jpg file would be great! Thanks a lot for this great tutorial and thanks in advance for your reply!

  231. alex 1 February 2011 at 5:45 am Permalink

    i tried to add radio buttons but keep getting ‘udetermined’ instead of my variable coming through

    any ideas?

  232. Aldo 1 February 2011 at 10:31 am Permalink

    Hi everybody! I´m from Argentina and we use the accents and the “ñ” letter, I’m testing this great form and I like it!! However I’ve a problem with special characters: Does it support utf-8? How can I set up it? Anybody can help me? Thank you very much!

    I would greatly appreciate an answer to my query.

  233. David 6 February 2011 at 3:21 am Permalink

    Many thank yous for this easy to follow tutorial. Works perfectly! Thank you.

  234. DanieloDesign 6 February 2011 at 4:07 am Permalink

    Gran tutorial! Muchas gracias =)

  235. Brad Maver 7 February 2011 at 1:55 am Permalink

    Great post, this is a nice, clean and simple contact form. Thanks!

  236. Moin Shaikh 7 February 2011 at 3:25 pm Permalink

    Thank you,
    Just wanna say that this is really a fantastic job u r doing. Just keep it up, i appreciate your hard work and am glad to have this form used.

    Once again,

    Thank you very much!

  237. ben 8 February 2011 at 12:20 am Permalink

    Nice code and tut.

    One thing that’s causing me probs is that if you fill out the form and click submit, the page is refreshed.

    Any way round that?

  238. Patutsnaman 9 February 2011 at 9:13 am Permalink

    nice one..ill try this soon

  239. Saurabh Gupta 17 February 2011 at 4:50 pm Permalink

    Thanks..>!! NIce Collection..

  240. Hitesh Patel 22 February 2011 at 2:07 am Permalink

    Hi…. Thank you so much for sharing with us

  241. Joseph 2 March 2011 at 11:53 pm Permalink

    Hi I’m using the form exactly as explained and have read all of the comments looking for deprecated PHP, but I can’t seem to get the form to send emails. I had it working in a test location, but now that it’s in the root directory it’s not working for some reason. Any help would be greatly appreciated. Thanks for the hard work regardless!

    belcosupply.com/contact.php

  242. Joseph 3 March 2011 at 2:07 am Permalink

    Please disregard my last comment. The issue was related to SMTP issues on the server’s side. THANKS!

  243. MT 5 March 2011 at 6:25 am Permalink

    One of the best tutorials. Well done! I’ve used with contact form very easily. Usually it takes so long to make it and finally is not working after a big process. Is that possible to ask the author to add recaptcha also please?

  244. Ricardo Rowe-Parker 5 March 2011 at 8:30 am Permalink

    Hello Raymond,

    Thank you SO much for taking the time to write this tutorial. I’ve found it invaluable so far. If you will let me know what your paypal account is I’ll be happy to make a contribution.

    They say a teacher usually knows more because “the more he/she teaches the more he/she learns”. Hopefully you’ve learned more by being generous with us.

    Your script is working, and I’m so happy about this.
    A couple of things are not working quite right, though:
    1) The string “This field is required” does not appear under each field as your tutorial shows. This string is linked to the “required” class and jQuery code. Instead, I get a string at the top of the box that says “Please check if you’ve filled all the fields with valid information. Thank you.” – that is being generated through the PHP script, though. So maybe the jQuery validation I’m using isn’t working, and I’m trying to figure out why.
    2) While linking to a jQuery API hosted by Google isn’t really my preference, it works and I can see why you’d use it (speed). I’m using jQuery 1.5.1, which appears to be the latest.

    This is a great tutorial; about a year old, but know that I spent almost 6 months looking for a tutorial like this one. Thanks a bunch.

    Ricardo

  245. Tonny 6 March 2011 at 6:16 am Permalink

    This is good form. I’m wondering how to send a multiple-item combo box selection with this form? Keep up the good work.

  246. Mi Kapa 9 March 2011 at 4:47 pm Permalink

    Thanks for this great tutorial. Worked like a charm from the first time. The comments also made me search less the web for minor improvements. Great work! Take care, and thanks again!