Wednesday, March 20, 2013

How to Create An Ajax-Based HTML5/CSS3 Contact Form

ontact form is deadly essential for any website, as it acts as a messenger which passes the opinion or enquiries of visitors to webmaster. There have been countless contact forms on the web but unfortunately most of them do not explain to you the inner working parts, so here comes a detailed tutorial to teach you to build an advanced contact form from scratch based on the pop technology, HTML5 and CSS3.
HTML5 contact form demo page
Considering the nature of a web-based e-mail contact form we are also required to dive into two separate application fields, which is the PHP backend code for sending email and jQuery functions for rich user interface. By the end we will be left with a fully dynamic and functional contact form written with later customization in mind.
Get started now to build your own advanced contact form!

Shortcut to:
  • Demo – Get a preview of what you are building
  • Download – Download all files (php + css)

Structuring the Application

To get started you’ll need some type of web server to work over. If you’re running a Windows machine WAMP is probably your best option. Mac users have a similar program named MAMP which is just as easy to install.
These packages will set up a local server on your machine with full access to PHP. Alternatively if you own server space or have full server access into a remote location you may use that instead. We are not going to need any MySQL databases, which should simplify things a bit.
Once your server is set up create a new folder to house the application. You can name this whatever you’d like as it isn’t detrimental or even related to the final product. The folder structure will be used when you access your files in a web browser. A simple example would be http://localhost/ajaxcontact/contact.php

Let’s Build our Files!

We will only be working within 2 core files. We’ll first need a core .php file to house not only our application logic, but also frontend HTML markup. Below is sample code taken from our starting file.
  1. <!DOCTYPE html>  
  2. <html xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en">   
  3. <head>   
  4. <title>HTML5/CSS Ajax Contact Form with jQuery</title>  
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>  
  6. <link href="styles.css" rel="stylesheet" type="text/css" />  
  7. </head>  
To begin we have written a simple heading section to our document. This includes a general Doctype declaration for HTML5 and some HTML/XML document elements. These aren’t exactly required, but will ease the rendering process in older (and newer) browsers. Also it never hurts to offer more information.
A bit further down we can see 2 lines right before our closing heading tag. The first includes our jQuery script from the online Google Code Repository. This is required for our dynamic page errors to work. Directly below this we have the inclusion of a basic CSS document containing all of our page styles.
Inside our document body we have a few containing divisions withholding a main contact form. This houses 3 input elements for the user’s name, e-mail address, and personal message. The HTML markup is fairly standard and shouldn’t boggle the mind of any intermediate developer.
  1. <!-- @begin contact -->  
  2. <div id="contact" class="section">  
  3.     <div class="container content">  
  4.           
  5.      <?php if(isset($emailSent) && $emailSent == true) { ?>  
  6.         <p class="info">Your email was sent. Huzzah!</p>  
  7.      <?php } else { ?>  
Here we have a basic PHP conditional code nested within a few page containers. This checks for the set value of a variable named $emailSent and if equal to true, it will display a success message.

Inside our Form HTML

The else statement is what will run on first page load since there won’t be any content to send initially. Inside here we will include a brief collection of form elements and a submit button.
  1. <div id="contact-form">  
  2.     <?php if(isset($hasError) || isset($captchaError) ) { ?>  
  3.         <p class="alert">Error submitting the form</p>  
  4.     <?php } ?>  
  5.                   
  6.     <form id="contact-us" action="contact.php" method="post">  
  7.         <div class="formblock">  
  8.         <label class="screen-reader-text">Name</label>  
  9.         <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />  
  10.           
  11.         <?php if($nameError != '') { ?>  
  12.             <br /><span class="error"><?php echo $nameError;?></span>   
  13.         <?php } ?>  
  14.           
  15.         </div>  
  16.                           
  17.         <div class="formblock">  
  18.         <label class="screen-reader-text">Email</label>  
  19.         <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />  
  20.           
  21.         <?php if($emailError != '') { ?>  
  22.             <br /><span class="error"><?php echo $emailError;?></span>  
  23.         <?php } ?>  
  24.           
  25.         </div>  
  26.                           
  27.         <div class="formblock">  
  28.             <label class="screen-reader-text">Message</label>  
  29.             <textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>  
  30.               
  31.         <?php if($commentError != '') { ?>  
  32.             <br /><span class="error"><?php echo $commentError;?></span>   
  33.         <?php } ?>  
  34.         </div>  
  35.                           
  36.         <button name="submit" type="submit" class="subbutton">Send us Mail!</button>  
  37.         <input type="hidden" name="submitted" id="submitted" value="true" />  
  38.     </form>             
  39. </div>  
  40.                   
  41. <?php } ?>  
  42. </div>  
  43. </div><!-- End #contact -->  
You may have noticed there is another conditional block directly after the starting form. This checks for a variable named $hasError and will display an error message upon confirmation. This fallback method is only used if JavaScript is disabled in the browser and thus can’t generate dynamic errors.
All the way down we can find individual PHP variables being checked. The statements are regulating if the form has already been submitted with only partial amounts of data filled in. This is another fallback system which displays the contents of fields already filled out – a nice trick for proper user experience!
Directly after our form completion is the few jQuery functions we’ve written. We will talk over these first since they are the default implementation on pageload. However if the browser doesn’t accept JavaScript then by default we can rely on our PHP code.

Opening to jQuery

The easiest way to get started talking on this topic would be to dive right in. I’ll break down individual blocks line-by-line so you can see what the script is actually checking for.
However if you get lost just review the project code files. All of the full blocks are pre-written and well documented in the jQuery website. To get started we open our code similar to any other:
  1. <script type="text/javascript">  
  2. <!--//--><![CDATA[//><!--  
  3. $(document).ready(function() {  
  4.     $('form#contact-us').submit(function() {  
The first few lines are checking for specific event occurrences. After our CDATA comments to hide the code from older, buggy browsers we get started checking for ready events.
The first bit checks if the document has fully loaded and is ready for manipulation. This is a classic technique and the easiest way to start coding a jQuery project.
Once inside we are checking for a form element under the ID "contact-us", and we want to know when it is submitted. Upon doing so we call another function to display our error messages or slideUp() upon success.
  1. $('form#contact-us .error').remove();  
  2. var hasError = false;  
  3. $('.requiredField').each(function() {  
  4.     if($.trim($(this).val()) == '') {  
  5.         var labelText = $(this).prev('label').text();  
  6.         $(this).parent().append('<span class="error">Your forgot to enter your '+labelText+'.</span>');  
  7.         $(this).addClass('inputError');  
  8.         hasError = true;  
  9.     } else if($(this).hasClass('email')) {  
  10.         var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
  11.         if(!emailReg.test($.trim($(this).val()))) {  
  12.             var labelText = $(this).prev('label').text();  
  13.             $(this).parent().append('<span class="error">Sorry! You\'ve entered an invalid '+labelText+'.</span>');  
  14.             $(this).addClass('inputError');  
  15.             hasError = true;  
  16.         }  
  17.     }  
  18. });  
First we remove any pre-existing errors so we don’t hold any previous messages from before. A few lines down we can see a selector for all elements under the class “requiredField“. These are all of our required field elements – name, e-mail, and message.
jQuery will take the value of each field and remove all spaces from the value. If the content is equal to nothing, then we display an error message next to that field warning our user to fill in some value. Right before the end of our logic there is a bit of Regex code validating the e-mail value.
Lastly we can see if no error is set and check for full input content. If this is the case we call a jQuery method named post(). This will submit our form and check within the PHP code for any errors. Assuming none are found the slideUp() animation is called to hide our contact form and display a “success!” message.
  1. if(!hasError) {  
  2.     var formInput = $(this).serialize();  
  3.     $.post($(this).attr('action'),formInput, function(data){  
  4.     $('form#contact-us').slideUp("fast"function() {                    
  5.         $(this).before('<p class="tick"><strong>Thanks!</strong> Your email has been delivered. Huzzah!</p>');  
  6.         });  
  7.     });  
  8.     }  
  9.               
  10.     return false;     
  11. });  
  12. });  
  13. //-->!]]>  
  14. </script>  
If you are familiar with callbacks you may notice the post() function has a built-in set of parameters. Callbacks are smaller functions which are called upon the response of data from another function.
So for example, when our jQuery.post() function successfully shoots an e-mail it will call its own internal function to display the sliding animation. All of this code could be written in its own block and moved elsewhere. However for the sake of this tutorial it’s much easier writing the callback as an inline function.

Breaking past our PHP

The final hurdle to mention is the logic behind our PHP processor. This is the backend system which will actually call a mail function and send out the message. All of the code used in the examples below can be found directly at the top of our main .php file, before any HTML output.
There are also a few internal styles which freshen up the page. There isn’t anything specifically new here so we won’t be going into any of the details. However the styles.css document is included within the project code and contains rudimentary CSS3 techniques.
  1. <?php   
  2. //If the form is submitted  
  3. if(isset($_POST['submitted'])) {  
To start we open our PHP clause and check if the form was even submitted. The POST variable “submitted” was actually a hidden input field added at the very end of our form. It’s a useful way to check if the user has submitted anything yet so we don’t waste server resources.
After this we have 3 separate if/else statement checking to see if each input field has been filled out. I won’t include each bit of logic here since they are all very repetitive in nature. However, to give you a brief example I’ve included the e-mail verification clause below:
  1. // need valid email  
  2. if(trim($_POST['email']) === '')  {  
  3.     $emailError = 'Forgot to enter in your e-mail address.';  
  4.     $hasError = true;  
  5. else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {  
  6.     $emailError = 'You entered an invalid email address.';  
  7.     $hasError = true;  
  8. else {  
  9.     $email = trim($_POST['email']);  
  10. }  
PHP will trim all whitespace from the value and check to see if anything is left over. If so we have a detailed Regular Expression (Regex) to see if our user’s input string matches up with an e-mail pattern.
You certainly don’t need to understand how preg_match() works to build this script. It is a useful function to determine rules and requirements for a successful type of data, but commands advanced programming knowledge to really grasp. In this scenario we are ensuring the user only inputs a select few characters, includes an @ symbol followed by 2-4 characters representing a Top-Level Domain.
After all of our logic passes and we return no errors it’s time to send our message! This bit of code will set individual variables to customize our e-mail message and setup some mail headers for the process.
  1. // upon no failure errors let's email now!  
  2.     if(!isset($hasError)) {  
  3.         $emailTo = 'youremailhere@googlemail.com'; 
  4.         $subject = 'Submitted message from '.$name; 
  5.         $sendCopy = trim($_POST['sendCopy']); 
  6.         $body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; 
  7.         $headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  
  8.   
  9.         mail($emailTo$subject$body$headers);  
  10.           
  11.         // set our boolean completion value to TRUE  
  12.         $emailSent = true;  
  13.     }  
If you were wondering how the code was going to figure out your e-mail address, this is the part to fill in. The first variable in our set is titled $emailTo and should contain whichever e-mail address, which is going to receive the message.
Inside our $body variable we take advantage of the \n delimiter to add new lines into the message. This adds small placements for the sender’s name, e-mail address, followed by a break for their message content. Of course you could spend time prettying up the display, but this structure works just fine.

Conclusion

This closes our tutorial for an advanced contact form. If you’d like to style your elements in relation to mine you can check out my example styles.css within the project code. However, the page is structured well enough that you could design your own look & feel very easily.
Feel free to download the source code and examine what I’ve done a bit closer. It’s good to follow a tutorial but having direct access to the project source can be invaluable. I’ve also included a brief stylesheet to make customizations a breeze, thanks for your view!

Courtesy: http://www.hongkiat.com/blog/ajax-html5-css3-contact-form-tutorial/

1 comment: