Home » » PHP contact form using jQuery validation

PHP contact form using jQuery validation


Hey! So, you need a PHP contact form with jQuery validation but don’t know how to build one right? No problem, i’m here to help. All you need is a server that supports php, and the client to have javascript enabled. In this tutorial we will show you how to build the contact form ( it’s a single page, yea ) and how to set it up on your server. First of all, check if your server supports the “mail()” function. You can do this by putting a simple PHP page on your server that has the fallowing code :
  1. <?php  
  2. phpinfo();  
  3. ?>  
Check to see if your results has something like “sendmail”. If you find that, we’re ok, you can send e-mails viamail() function. We’re ok ? Let’s start…
Step 1 : Creating the HTML form ( page )
OK, now we have to create our html contact form page. Create a new page ( give it any name you want as long as it has the php extension ). Creating a PHP page will help us to display everything in only one page, and not have multiple ones. We also going to use a PHP constant for the action on the form. The constant will represent the url for the current filename ( relative to the document root ). This will ensure us that after pressing the send button the page is the same.
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
  2.         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  
  4.   
  5. <head>  
  6.     <title>PHP Contact Form with JQuery Validation</title>  
  7.     <meta http-equiv="content-type" content="text/html;charset=utf-8" />  
  8.     <meta http-equiv="Content-Style-Type" content="text/css" />  
  9.   
  10.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>  
  11.   
  12.     <style type="text/css">  
  13.   
  14.     </style>  
  15. </head>  
  16.   
  17. <body>  
  18. <div id="contact-wrapper">  
  19.     <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">  
  20.         <div>  
  21.             <label for="name"><strong>Name:</strong></label>  
  22.             <input type="text" size="50" name="contactname" id="contactname" value="" />  
  23.         </div>  
  24.   
  25.         <div>  
  26.             <label for="email"><strong>Email:</strong></label>  
  27.             <input type="text" size="50" name="email" id="email" value="" />  
  28.         </div>  
  29.   
  30.         <div>  
  31.             <label for="subject"><strong>Subject:</strong></label>  
  32.             <input type="text" size="50" name="subject" id="subject" value="" />  
  33.         </div>  
  34.   
  35.         <div>  
  36.             <label for="message"><strong>Message:</strong></label>  
  37.             <textarea rows="5" cols="50" name="message" id="message"></textarea>  
  38.         </div>  
  39.         <input type="submit" value="Send Message" name="submit" />  
  40.     </form>  
  41. </div>  
  42. </body>  
  43. </html>  
Step 2 : Let’s color it a little bit
  1. body {  
  2.     font-family:Arial, Tahoma, sans-serif;  
  3. }  
  4. #contact-wrapper {  
  5.     width:430px;  
  6.     border:1px solid #e2e2e2;  
  7.     background:#f1f1f1;  
  8.     padding:20px;  
  9. }  
  10. #contact-wrapper div {  
  11.     clear:both;  
  12.     margin:1em 0;  
  13. }  
  14. #contact-wrapper label {  
  15.     display:block;  
  16.     float:none;  
  17.     font-size:16px;  
  18.     width:auto;  
  19. }  
  20. form#contactform input {  
  21.     border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;  
  22.     border-style:solid;  
  23.     border-width:1px;  
  24.     padding:5px;  
  25.     font-size:16px;  
  26.     color:#333;  
  27. }  
  28. form#contactform textarea {  
  29.     font-family:Arial, Tahoma, Helvetica, sans-serif;  
  30.     font-size:100%;  
  31.     padding:0.6em 0.5em 0.7em;  
  32.     border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;  
  33.     border-style:solid;  
  34.     border-width:1px;  
  35. }  
If everything worked ok, the output of the page should look like the one bellow.
Contact form using php and jquery
Step 3 : Validate using JQuery
If you haven’t seen yet, we already putted this line in the HTML ( PHP ) page created above.
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>  
Loading JQuery alone is only the first part. We also 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. Then reference it like bellow.
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>  
  2. <script src="jquery.validate.pack.js" type="text/javascript"></script>  
Now we need to initialize the JQuery : Validation plugin in order to work. Keep in mind that “#contactform” is the id value of the form.
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>  
  2. <script src="jquery.validate.pack.js" type="text/javascript"></script>  
  3.   
  4. <script type="text/javascript">  
  5. $(document).ready(function(){  
  6.     $("#contactform").validate();  
  7. });  
  8. </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”. Bellow is an update for the form with the classes already written.
  1. <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">  
  2.     <div>  
  3.         <label for="name"><strong>Name:</strong></label>  
  4.         <input type="text" size="50" name="contactname" id="contactname" value="" class="required" />  
  5.     </div>  
  6.   
  7.     <div>  
  8.         <label for="email"><strong>Email:</strong></label>  
  9.         <input type="text" size="50" name="email" id="email" value="" class="required email" />  
  10.     </div>  
  11.   
  12.     <div>  
  13.         <label for="subject"><strong>Subject:</strong></label>  
  14.         <input type="text" size="50" name="subject" id="subject" value="" class="required" />  
  15.     </div>  
  16.   
  17.     <div>  
  18.         <label for="message"><strong>Message:</strong></label>  
  19.         <textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>  
  20.     </div>  
  21.     <input type="submit" value="Send Message" name="submit" />  
  22. </form>  
Step 4 : 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.
  1. <?php  
  2. //If the form is submitted  
  3. if(isset($_POST['submit'])) {  
  4.   
  5.     //Check to make sure that the name field is not empty  
  6.     if(trim($_POST['contactname']) == '') {  
  7.         $hasError = true;  
  8.     } else {  
  9.         $name = trim($_POST['contactname']);  
  10.     }  
  11.   
  12.     //Check to make sure that the subject field is not empty  
  13.     if(trim($_POST['subject']) == '') {  
  14.         $hasError = true;  
  15.     } else {  
  16.         $subject = trim($_POST['subject']);  
  17.     }  
  18.   
  19.     //Check to make sure sure that a valid email address is submitted  
  20.     if(trim($_POST['email']) == '')  {  
  21.         $hasError = true;  
  22.     } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {  
  23.         $hasError = true;  
  24.     } else {  
  25.         $email = trim($_POST['email']);  
  26.     }  
  27.   
  28.     //Check to make sure comments were entered  
  29.     if(trim($_POST['message']) == '') {  
  30.         $hasError = true;  
  31.     } else {  
  32.         if(function_exists('stripslashes')) {  
  33.             $comments = stripslashes(trim($_POST['message']));  
  34.         } else {  
  35.             $comments = trim($_POST['message']);  
  36.         }  
  37.     }  
  38.   
  39.     //If there is no error, send the email  
  40.     if(!isset($hasError)) {  
  41.         $emailTo = 'youremail@yoursite.com<script type="text/javascript"> 
  42. /* <![CDATA[ */ 
  43. (function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__");a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})(); 
  44. /* ]]> */ 
  45. </script>'//Put your own email address here  
  46.         $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";  
  47.         $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  
  48.   
  49.         mail($emailTo, $subject, $body, $headers);  
  50.         $emailSent = true;  
  51.     }  
  52. }  
  53. ?>  
Ok, we are almost finish. All we have to do is insert a little more PHP code to output two kinds of messages. The first message is to notify us in case there were errors or any other problems after the submission, and the other is a message to tell us that the email was sent and there were no problems. The code for that will just sit right inside the contact-wrapper div but right before the jQuery contact form markup.
  1. <?php if(isset($hasError)) { //If errors are found ?>  
  2.     <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>  
  3. <?php } ?>  
  4.   
  5. <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>  
  6.     <p><strong>Email Successfully Sent!</strong></p>  
  7.     <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>  
  8. <?php } ?>  
We are now done :)
You just 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 you are ready to go!. If you enjoyed the tutorial, please share it with others using the icons bellow. And if you want to congratulate me, post a comment, send me a beer ( via e-mail ) or anything you have in mind. Before we finish, I’ve putted the full code bellow. Regards…
  1. <?php  
  2. //If the form is submitted  
  3. if(isset($_POST['submit'])) {  
  4.   
  5.     //Check to make sure that the name field is not empty  
  6.     if(trim($_POST['contactname']) == '') {  
  7.         $hasError = true;  
  8.     } else {  
  9.         $name = trim($_POST['contactname']);  
  10.     }  
  11.   
  12.     //Check to make sure that the subject field is not empty  
  13.     if(trim($_POST['subject']) == '') {  
  14.         $hasError = true;  
  15.     } else {  
  16.         $subject = trim($_POST['subject']);  
  17.     }  
  18.   
  19.     //Check to make sure sure that a valid email address is submitted  
  20.     if(trim($_POST['email']) == '')  {  
  21.         $hasError = true;  
  22.     } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {  
  23.         $hasError = true;  
  24.     } else {  
  25.         $email = trim($_POST['email']);  
  26.     }  
  27.   
  28.     //Check to make sure comments were entered  
  29.     if(trim($_POST['message']) == '') {  
  30.         $hasError = true;  
  31.     } else {  
  32.         if(function_exists('stripslashes')) {  
  33.             $comments = stripslashes(trim($_POST['message']));  
  34.         } else {  
  35.             $comments = trim($_POST['message']);  
  36.         }  
  37.     }  
  38.   
  39.     //If there is no error, send the email  
  40.     if(!isset($hasError)) {  
  41.         $emailTo = 'youremail@yoursite.com<script type="text/javascript"> 
  42. /* <![CDATA[ */ 
  43. (function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__");a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})(); 
  44. /* ]]> */ 
  45. </script>'//Put your own email address here  
  46.         $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";  
  47.         $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  
  48.   
  49.         mail($emailTo, $subject, $body, $headers);  
  50.         $emailSent = true;  
  51.     }  
  52. }  
  53. ?>  
  54. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
  55.         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
  56. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  
  57.   
  58. <head>  
  59.     <title>PHP Contact Form with JQuery Validation</title>  
  60.     <meta http-equiv="content-type" content="text/html;charset=utf-8" />  
  61.     <meta http-equiv="Content-Style-Type" content="text/css" />  
  62.   
  63. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>  
  64. <script src="jquery.validate.pack.js" type="text/javascript"></script>  
  65.   
  66. <script type="text/javascript">  
  67. $(document).ready(function(){  
  68.     $("#contactform").validate();  
  69. });  
  70. </script>  
  71.   
  72. <style type="text/css">  
  73. body {  
  74.     font-family:Arial, Tahoma, sans-serif;  
  75. }  
  76. #contact-wrapper {  
  77.     width:430px;  
  78.     border:1px solid #e2e2e2;  
  79.     background:#f1f1f1;  
  80.     padding:20px;  
  81. }  
  82. #contact-wrapper div {  
  83.     clear:both;  
  84.     margin:1em 0;  
  85. }  
  86. #contact-wrapper label {  
  87.     display:block;  
  88.     float:none;  
  89.     font-size:16px;  
  90.     width:auto;  
  91. }  
  92. form#contactform input {  
  93.     border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;  
  94.     border-style:solid;  
  95.     border-width:1px;  
  96.     padding:5px;  
  97.     font-size:16px;  
  98.     color:#333;  
  99. }  
  100. form#contactform textarea {  
  101.     font-family:Arial, Tahoma, Helvetica, sans-serif;  
  102.     font-size:100%;  
  103.     padding:0.6em 0.5em 0.7em;  
  104.     border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;  
  105.     border-style:solid;  
  106.     border-width:1px;  
  107. }  
  108. </style>  
  109. </head>  
  110.   
  111. <body>  
  112.     <div id="contact-wrapper">  
  113.   
  114.     <?php if(isset($hasError)) { //If errors are found ?>  
  115.         <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p> 
  116.     <?php } ?> 
  117.  
  118.     <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?> 
  119.         <p><strong>Email Successfully Sent!</strong></p> 
  120.         <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> 
  121.     <?php } ?> 
  122.  
  123.     <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">  
  124.         <div>  
  125.             <label for="name"><strong>Name:</strong></label>  
  126.             <input type="text" size="50" name="contactname" id="contactname" value="" class="required" />  
  127.         </div>  
  128.   
  129.         <div>  
  130.             <label for="email"><strong>Email:</strong></label>  
  131.             <input type="text" size="50" name="email" id="email" value="" class="required email" />  
  132.         </div>  
  133.   
  134.         <div>  
  135.             <label for="subject"><strong>Subject:</strong></label>  
  136.             <input type="text" size="50" name="subject" id="subject" value="" class="required" />  
  137.         </div>  
  138.   
  139.         <div>  
  140.             <label for="message"><strong>Message:</strong></label>  
  141.             <textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>  
  142.         </div>  
  143.         <input type="submit" value="Send Message" name="submit" />  
  144.     </form>  
  145.     </div>  
  146. </body>  
  147. </html>  
Share this article :

0 comments:

Post a Comment

 
Support : News | Adsense Trick
Copyright © 2011. Webs Tech - A Technology Blog - All Rights Reserved
Proudly powered by Blogger