Wednesday, July 31, 2013

My Wordpress learning series -Validating submitting and emailing a contact form using jquery and PHP

For many of you who use “jquery.validate.js” to validate your forms, you may be keen for a solution that not only submits the form and emails the content but also displays a ‘thank you’ message after successful submission and all within the same handler .I am focussing on the same handler as you will find 100’s of solutions to submit it using another function but not within the same validate function.

So, here’s a full proof resolution for you after putting in hours of hard work. Since I use wordpress for most of my projects, I'd like to put forth a solution that would work along with your wordpress themes as well.

I am not using any contact form wordpress plugins here, but simply combining the power of PHP and jquery to accomplish the desired output. I’m a huge advocate of building things from scratch rather than use WP plugins mainly because you really need to hack the core to get it working as per your need. So let’s begin the journey and get going..

Create a new file say “contact.php” in your theme folder and put this code in it.I won’t get into the details of each line as there are loads of tutorials that would teach you how to build a simple PHP form.

To summarize, the code below validates the form and sends out an email after successful submission. Please note that I am using both jquery and PHP to validate the form for fallbacks.To know more about the jquery validate plugin,you can visit: http://jqueryvalidation.org/validate/

contact.php 

<?php get_header(); ?>
<?php //If the form is submitted   
if(isset($_POST['submitted'])) {
                   if(trim($_POST['contactName']) === '') {
                             $nameError = 'You forgot to enter your name.';
                             $hasError = true;
                   } else {
                             $name = trim($_POST['contactName']);
                   }       
         
        if(trim($_POST['email']) === '')  {
               $emailError = 'Please enter your email address.';
               $hasError = true;
        } else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
               $emailError = 'You entered an invalid email address.';
               $hasError = true;
        } else {
               $email = trim($_POST['email']);
        }
                             $phone = trim($_POST['phone']);
                             $comments = trim($_POST['comment']);


        if(!isset($hasError)) {

                  
               $emailTo = get_option('tz_email');
               if (!isset($emailTo) || ($emailTo == '') ){
                       $emailTo = get_option('admin_email');
               }
               $subject = '[Test email] From '.$name;
               $body = "Name: $name \n\nEmail: $email \n\nContact #: $phone \n\nComments: $comments";
               $headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

               wp_mail($emailTo, $subject, $body, $headers);
               $emailSent = true;
        }

} ?>                      

<div class="content">
   <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
                       <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                                      <div>
                                              <?php if(isset($emailSent) && $emailSent == true) {                                             
                                                                                        
                                                                                                 ?>                                                                                            
                                                      <div class="msg">
                                                                                          <p>
                                                                                         
                                                                                                </p>
                                                             <p>Thanks, <?=$name;?> your email was sent successfully.</p>
                                                             <br><br><br>
                                           </div>
                                              <?php } else { ?>
                                                      <?php the_content(); ?>
                                                      <?php if(isset($hasError)) { ?>
                                                             <p>There was an error submitting the form.<p>
                                                      <?php } ?>
                                                       <?php } ?>
                                                       <?php endwhile; endif; ?>



<div class="form">
                                      <form class="form-horizontal " action="<?php the_permalink(); ?>" id="contactForm" method="post" >
                                      <fieldset>
                                          <div class="control-group">
                                            <label class="control-label" for="name">Name(*)</label>
                                            <div class="controls">
                                              <input type="text" class="input-medium required" id="contactName" name="contactName">
                                               <?php if($nameError != '') { ?>
                                                                                                                                                                                                                                                  <div class="control-group error">                                                                   
                                                                                                                                                                                                                                                 <span class="help-inline"><?=$nameError;?></span>
                                                                                                                                                                                                                                                 </div>
                                                             <?php } ?>

                                            </div>
                                          </div>
                                          <!-- Email -->
                                          <div class="control-group">
                                            <label class="control-label" for="email">Email(*)</label>
                                            <div class="controls">
                                              <input type="text" class="input-medium required" id="email" name="email">
                                              <?php if($emailError != '') { ?>
                                                              <div class="control-group error">      
                                                                     <span class="help-inline"><?=$emailError;?></span>
                                                              </div>      
                                                             <?php } ?>

                                            </div>
                                          </div>
                                          <div class="control-group">
                                            <label class="control-label" for="phone">Phone No.</label>
                                            <div class="controls">
                                              <input type="text" class="input-medium" id="phone" name="phone">
                                            </div>
                                          </div>
                                          <div class="control-group">
                                            <label class="control-label" for="comment">Message</label>
                                            <div class="controls">
                                              <textarea class="input-medium" id="comment" rows="3" name="comment"></textarea>
                                            </div>
                                          </div>
                                           <div id="loading">Submitting form</div>
                                          <div class="form-actions"> 
                                            <button type="submit" class="btn-submit">Submit</button>
                                            <button type="reset" class="btn-reset">Reset</button>
                                          </div>
                                          <input type="hidden" name="submitted" id="submitted" value="true" />
                                                                                                                                                                </fieldset>

                                      </form>
                                     </div>
<?php get_footer(); ?>

Now we will add “jquery.validate.js” inside footer.php as given below:

<script src="<?php bloginfo('template_url'); ?>/js/jquery.validate.js"></script>

Now go ahead and define the jquery function .I have defined all my jquery scripts inside custom.js . Don't forget to include it in your footer.php file.


custom.js
$(document).ready(function() {               
$("form#contactForm").validate({
  rules: {
     email: {
      email: true
    },
    phone: {
      digits: true
    }
  },
  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"
    },
    phone: {
      digits: "Please enter numbers only"
    }
  },
  submitHandler: function(form) {
    var $form=$("form#contactForm");
  $form.css({'cursor':'wait'});
 $(".form-actions").hide();
$("#loading").show();
    var data= $form.serialize();
                var url=$form.attr('action');
    $.ajax({
    type: "POST",
    url: url,
    data: data,
     success: function(data, textStatus, jqXHR) {
                 $form.before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I will be in touch soon.</p>');
              $form.css({'cursor':'default'});
                                                   $(".form-actions").show();
                                                                $("#loading").hide();
                                                                $form[0].reset();
                }
    });
    return false;
               
});
What the function above does it to validate the fields that have “required” attached to them in our earlier created php file.



For e.g. <input type="text" class="input-medium required" id="email" name="email">

I have also added some more validations for email and phone number. The magic happens inside the “submitHandler: function(form)”  handler. It submits the form once all the required fields have been filled .It also does some additional useful stuff like changing the cursor to a wait while the form is being submitted and changes the text to “Submitting form”( <div id="loading">Submitting form</div> does this. Remember to hide it in your css ) to give an indication to the user that the form submission is in progress. What’s more? It also displays a thank you message after the form is successfully submitted and changes the cursor back and resets the form fields. Pretty cool, isn’t it?









Post a Comment