CSS / Dev / HTML / JQuery / PHP

How To Make a Contact Form with PHP, JQuery, HTML and CSS

It’s a common thing. A client asks you to make a simple form with a bit of validation. Add a bit of feedback to inform the user of wrong inputs as well as successes. So to start we need to build our form. Let’s keep it simple for this tutorial.

HTML

Let’s start with a simple HTML structure.

<div id="contact">
<form action="" method="post" accept-charset="utf-8" id="contact-form">
<div id="form-status" class="red"></div>
 <h3>Contact Form</h3>
 <ul>
 <li>
 <label for="name">Name</label>
 <input type="text" name="name" id="name">
 </li>
 <li>
 <label for="email">Email</label>
 <input type="text" name="email" id="email">
 </li>
 <li>
 <label for="message">Message</label>
 <textarea type="text" name="message" id="message"></textarea>
 </li>
 <li> 
 <input type="text" name="secret" id="secret">
 <input type="submit" name="submit" id="submit" value="Submit">
 </li>
 </ul>

</form>
</div>

You’ll end up with something like this:

Pretty Basic

Pretty Basic

Bland but workable. You’ll also notice a form-status div and an input with and id of “secret”. The form-status will be used for providing form feedback to the user.

The secret input is a simple anti-spam feature. Spambots usually fill in all fields. We’ll hide it with CSS in the next section. Since this field is hidden from human users, it will always be left blank.

Here’s an article enumerating several ways to prevent spam: Are you human? is CAPTCHA needed? Some Alternatives.
I just used one of the most basic for this example.

CSS

Let’s add a bit of CSS to make it more pretty:

 ul{ margin: 0; padding: 0;}
 li{ list-style: none;}
 h3{
 text-align: center;
 }
 #contact{
 margin: 50px auto;
 padding: 20px;
 width: 300px;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 -webkit-box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.3);
 background-color: #eaf1fb;
 font-family: Verdana, arial, sans-serif;
 }
 #contact-form{ width: 300px;}
 #contact-form label{
 width: 100px; 
 display: inline-block;
 padding: 5px 5px 0 0;
 float: left;
 box-sizing: border-box;
 text-align: right;
 font-size: 0.8em;
 font-weight: bold;
 }
 #contact-form input[type=text], 
 #contact-form textarea{
 width: 200px; 
 margin: 0 0 10px 0; 
 padding: 5px; 
 float: left;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 background-color:#fff;
 border: 1px solid #abadb3;
 outline: none;
 }
 #contact-form input[type=text]:focus, 
 #contact-form textarea:focus{
 -webkit-box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 -moz-box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3);
 }
 #contact-form textarea{
 height:80px;
 resize:vertical;
 }
 #contact-form input[type=submit]{
 -webkit-border-radius: 10px;
 border-radius: 10px;
 padding: 5px 15px; 
 color: #eaf1fb;
 background-color:#0473dd;
 border: 1px solid #fff;
 }
 #contact-form input[type=submit]:hover{
 cursor: hand;
 color: #0473dd;
 background-color:#aac3ea;
 }
 #contact-form li:last-child{text-align: right;}
 #contact-form input#secret{ display:none; }
 #form-status{
 padding: 10px;
 display: none;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 }
 #form-status.display{ display: block;}
 #form-status.green{ 
 color: #044c29;
 background-color:#96ed89;
 border: 1px solid #044c29;
 }
 #form-status.red{ 
 color: #bf1616;
 background-color:#ff837e;
 border: 1px solid #bf1616;
 }

That’s a lot of CSS. But very much worth it. This is what we get:

And it's even centered on the page! :)

And it’s even centered on the page! 🙂

I’ll go through it step by step.

 ul{ margin: 0; padding: 0;}
 li{ list-style: none;}
 h3{
 text-align: center;
 }

This is just some formatting.

 #contact{
 margin: 50px auto;
 padding: 20px;
 width: 300px;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 -webkit-box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.3);
 background-color: #eaf1fb;
 font-family: Verdana, arial, sans-serif;
 }
 #contact-form{ width: 300px;}

I’ve set the margin to center the contact form and added CSS3 box shadows and border radius. I used CSS3 Generator to create the corners, shadows, and border effects. It’s very handy and convenient to use. I’ve also set the width to 300px since it’ll be a simple form.

 #contact-form label{
 width: 100px; 
 display: inline-block;
 padding: 5px 5px 0 0;
 float: left;
 box-sizing: border-box;
 text-align: right;
 font-size: 0.8em;
 font-weight: bold;
 }

For the labels I’ve set it to a standard width with a bit of padding to align it well with the text fields and text area.I’ts also floated left so each label lines up with their respective field. I’ve set box sizing to border-box so that when I set the padding it will not add to the overall width of the element.

 #contact-form input[type=text], 
 #contact-form textarea{
 width: 200px; 
 margin: 0 0 10px 0; 
 padding: 5px; 
 float: left;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 background-color:#fff;
 border: 1px solid #abadb3;
 outline: none;
 }

For the actual input fields, I set a fixed width and add a 10px margin for even spacing. I also added a 5px padding to emphasize the rounded corners.

Also, take note of outline: none;, which removes the default outline/glow on your browser when it’s in focus. We’ll be replacing that with a proper shape with rounded corners as well.

 #contact-form input[type=text]:focus, 
 #contact-form textarea:focus{
 -webkit-box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 -moz-box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3); 
 box-shadow: inset 1px 1px 2px 1px rgba(0, 0, 0, 0.3);
 }

This bit of CSS is to replace the default outline/glow.

 #contact-form textarea{
 height:80px;
 resize:vertical;
 }

Next we set the default height of the text area and restrict the resize function to vertical so it won’t wreck out layout when the user decides to expand the area.

#contact-form input[type=submit]{
 -webkit-border-radius: 10px;
 border-radius: 10px;
 padding: 5px 15px; 
 color: #eaf1fb;
 background-color:#0473dd;
 border: 1px solid #fff;
 }
 #contact-form input[type=submit]:hover{
 cursor: hand;
 color: #0473dd;
 background-color:#aac3ea;
 }
 #contact-form li:last-child{text-align: right;}
 #contact-form input#secret{ display:none; }

If you try to render a submit input in different browsers, it will usually be a grey button with a lot of different appearances. We don’t want that for our form. So we add a bit of styling for the submit button. We’ll also make sure that the cursor changes into a hand when we hover over it to preserve that button experience.

We’ll also align the submit button to the right by using the last-child selector on the  li containing it as well as hiding the secret field.

 #form-status{
 padding: 10px;
 display: none;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 }
 #form-status.display{ display: block;
 }
 #form-status.green{
 color: #044c29;
 background-color:#96ed89;
 border: 1px solid #044c29;
 }
 #form-status.red{
 color: #bf1616;
 background-color:#ff837e;
 border: 1px solid #bf1616;
 }

If you’ll go back to the HTML Form we made, there’s a small div at the top with the id of form-status. This is where we’ll display error/success messages for the users.

We’ll hide it by default and add two classes to show errors and successes – red and green, respectively. We’ll also keep that rounded corners theme going.

Here’s a nice tip, if you need a quick color scheme or are lacking in visual skills, find a scheme generator. Here’s two:

  • Adobe’s kuler – has a search of user submitted color schemes. You can even add your own.
  • Peter Stanicek’s Color Scheme Designer – Make your own color scheme by using the fancy color wheel UI and other handy tools.

PHP

Okay, so once you’re done tweaking and playing around with the visuals of the form we’ll go into the programming bits starting with PHP.

$rm = $_SERVER['REQUEST_METHOD'];
$stat_message = "We've received your submission! Thank you!";
$posted = false;
$success = false;

First we assign and create some variables. When the form is submitted, it creates a request to the server using either a POST or a GET request method. The $_SERVER[‘REQUEST_METHOD’] stores that information. If you’ll check the <form> tag in our code, you’ll see a “method” attribute that we set to “post”.

Here’s the basic difference between a POST and a GET:

Either way works but a good rule of thumb is to always use POST when the data is sensitive of will submit something to the DB.

We also add a variable for the status message – this is hidden by default so you can set it to anything – and two more variable that we’ll use later for our logic.

//if the request method is post
if ($rm == 'POST') {
 // this will be used in our logic later.
 $posted = true;

 // we'll run it through a filter to remove special characters. Another security precaution.
 // we'll use these variable later in our logic as well as to refill in the values after a form submission refresh.
 $name = htmlspecialchars($_POST['name']);
 $email = htmlspecialchars($_POST['email']);
 $message = htmlspecialchars($_POST['message']);
 $secret = htmlspecialchars($_POST['secret']);
 // check if all items aren't blank. If the form is incomplete, set a feedback message.
 // also make sure that the hidden secret input is blank.
 if( $name != "" &&
     $email != "" &&
     $message != "" &&
     $secret == ""){
  //check if email is valid. If not set a feedback message.
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

   // we'll compose the email message next.
   $to = 'you@mysite.com';
   $subject = 'Contact Form Submission from '.$name;

   // This is what you would call a heredoc. Heredoc syntax was developed so you won't have to keep escaping strings.
   // Just make sure to remove indentations since they will also be included in the heredoc.
   $mail_message = <<<EOT
A message has been sent through the Contact Form.
Sender: $name
Email: $email
message: $message
EOT;
   // These are some other requirements in creating an email message.
   $headers = 'MIME-Version: 1.0' . "\r\n";
   $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
   $headers .= 'From: contact@mysite.com' . "\r\n" .
   'Reply-To: contact@mysite.com' . "\r\n" .
   'X-Mailer: PHP/' . phpversion();

   // Here we try to send the message and set $success to true if it succeeds. If it fails then set a feedback message.
   if(mail($to, $subject, $mail_message)){
    $stat_message = 'Thank you for your message.';
    //this will be used in our logic later as well.
    $success = true;
   } else{
   $stat_message = 'There was a problem sending your message.';
   }
  } else{
  $stat_message = "Please enter a valid email address.";
  }
 } else{
  $stat_message = "Please fill up all the fields.";
 }
}

I added some comments in the code above to more easily explain the logic line by line.

Here’s a good explanation of what a heredoc is.

Here’s how to send an email in PHP.

To simplify, the code determines if the form was submitted, if the information is valid and complete, then tries to send the message. If any problems are encountered along the way, set a feedback message. We’ll show a feedback message in the form-status div later using some jquery.

If you’ll test the form now, and input incomplete or invalid values, you’ll see that all the values are erased after submission. Now that can be a pain for the user, but we can solve that by inserting some PHP into the HTML markup.

 <li>
  <label for="name">Name</label>
  <input type="text" name="name" id="name" <?php if($posted && $success == false){ echo "value= \"$name\""; } ?> >
 </li>
 <li>
  <label for="email">Email</label>
  <input type="text" name="email" id="email" <?php if($posted && $success == false){ echo "value= \"$email\""; } ?> >
 </li>
 <li>
  <label for="message">Message</label>
  <textarea type="text" name="message" id="message"><?php if($posted && $success == false){ echo $message; } ?></textarea>
 </li>

If the form was posted and there was an error, write the user-entered values into the fields again. If you’ll notice the format is different for different input field types.

We’re almost done. We just have to make the feedback functionality work which is easy with a bit of PHP and JQuery.

A Bit of PHP with JQuery

Ok, so since the form-status is supposed to be hidden when the form is initially displayed we can hide it with some PHP. And I know what you’re gonna say “Japs, we already hid it with CSS!”, but indulge me a bit.

Even if the CSS hides the bit of code from displaying, the code is still there. Don’t believe me?  Right click your page and view the source. It’s there! So let’s hide it better. 🙂

 <?php if ($posted): ?>
  <div id="form-status" class="red"><?php echo $stat_message; ?></div>
 <?php endif; ?>

If the form was submitted/posted, the bit of HTML is rendered.

Next we add JQuery to make the form-status appear – in a fancy fade-in fashion. Add the following to the bottom of your form:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

import the JQuery Library.

<script type="text/javascript" charset="utf-8" >
$(document).ready(function(){
 // assign a variable to reference the form-status
 form_status = $('#form-status');
 // if the mail was sent, change the color of form-status.
 // I used the CSS classes we made before.
 <?php if ($success): ?>
 form_status.removeClass('red').addClass('green');
 <?php endif; ?>
 // if the form was submitted, then show the status using a JQuery fade.
 <?php if ($posted): ?>
 form_status.fadeIn(1000); 
 <?php endif; ?>
});
</script>

I added some comments inline. This is what you get:

This will be green on a successful submission.

This will be green on a successful submission.

Adding a bit of JQuery is a pretty simple way to make your form just a bit more awesome.

If you want to learn JQuery, Code School has an online interactive course that you can go through on your own time.

Try JQuery is a collection of videos and challenges that make learning easy, fun, and fast.

So that’s it. I hope you had fun reading this tutorial. The resources, links, and source code are listed below.

Links and Resources:

Source Code:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s