Today we’re going to learn how to make an Ajax contact form using Jquery.  This is a nearly identical implementation to what we use on our contact form.  Overall this is a simple contact form, the user inputs their name, email address and message, then clicks the send button.  From there the javascript validates the data.  Once validated we use Jquery’s ajax() function to pass the data to a PHP file and finally send the message.   This form is W3C valid and compatible with IE6+, Firefox, Chrome, Safari and Opera.  View the demo here.

The Form

First we will start by creating the markup for the form itself:

<form id="contact_form" onsubmit="return validate_form()" action="" method="post">
<div id="contact_form_content">
<label id="contact_name" for="name">Name:</label>
<input onfocus="$('#name_error').fadeOut('fast');" onclick="$('#name_error').fadeOut('fast');" type ="text" name="name" id="name" /><br/>
<label id="contact_email" for="email">Email:</label>
<input onfocus="$('#email_error').fadeOut('fast');" onclick="$('#email_error').fadeOut('fast');" type="text" name="email" id="email" /><br/>
<label id="contact_message" for="message">Message:</label>
<textarea onfocus="$('#message_error').fadeOut('fast');" onclick="$('#message_error').fadeOut('fast');" id ="message" rows="8" cols ="20"></textarea>
<img id="loader" src="ajax-loader.gif" alt="Processing" height="16" width="16"/>
<input id ="submit_button" type="submit" value ="Send" name="submit"/>
</div>
</form>

As you can see, the markup is fairly straightforward, but there are a few points to highlight.  Notice that the form’s action declaration is empty, instead we use the onsubmit event to do all of the work.  Finally you may be wondering why the inputs have both onfocus and onclick events.  Those two events are present simply for browser compatibility, namely IE has trouble with the onlick event.

The CSS

This portion is purely optional, but can offer you a foundation for styling the entire form.  Copy this CSS as you see fit:

body{
font-size:14px;
font-family: tahoma,geneva,arial;
background-color: #f2f2f2;
}
p{
text-align: center;
}
form{
width:426px;
font-size:1.4em;
margin: 0 auto;
position:relative;
}
form label{
float:left;
margin-right:40px;
text-align:right;
width:80px;
}
form input{
height:22px;
width:300px;
margin-bottom:10px;
}
textarea {
width: 300px;
}
#submit_button{
background-color: #CBDF6F;
border: 1px solid #9EB253;
cursor: pointer;
float: right;
font-weight: bold;
height: 31px;
margin-top: 10px;
width: 50px;
}
form .error{
background-color:#F2E9E1;
border:2px dashed #9EB253;
display:none;
font-size:0.7em;
font-weight:bold;
padding:4px;
position:absolute;
z-index:1;
}
form #name_error{
right: -89px;
top: -5px;
}
form #email_error{
right: -155px;
top: 34px;
}
form #message_error{
right: -111px;
top: 74px;
}
form #send_message{
left: 110px;
line-height: 2em;
padding: 10px;
text-align: center;
top: 40px;
-moz-box-shadow: 5px 5px 7px #AAAAAA;
-webkit-box-shadow:5px 5px 7px #aaaaaa;
box-shadow:5px 5px 7px #aaaaaa;
}
#loader{
display:none;
bottom: -33px;
position: absolute;
right: 65px;
}

Overall this is standard CSS code so I won’t go over the specifics.

Jquery

Here is the Jquery code.  Remember to have the latest version of Jquery (version 1.4.4 at time of writing) loaded in yourtag for this to work:

function validate_form(){
        var error = 0;
        $("#name_error").detach();
        $("#email_error").detach();
        $("#message_error").detach();
        if (document.getElementById('name').value =='' || document.getElementById('name').value == null){
            $('#name').after('<span class="error" id="name_error">Please enter your name</span>');
           $("#name_error").fadeIn('slow');
            error = 1;
       }
        var _regexp = new RegExp(/^([0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9})$/);
        var _email = document.getElementById('email').value;
        if(_regexp.test(_email) == false) {
            $('#email').after('<span class="error" id="email_error">Please enter a valid email address</span>');
            $("#email_error").fadeIn("slow");
            error = 1;
        }
        if (document.getElementById('message').value =='' || document.getElementById('message').value == null){
            $('#message').after('<span class="error" id="message_error">Please enter your message</span>');
            $("#message_error").fadeIn("slow");
            error = 1;
        }
        if (error == 1){
            return false;
        }else{
            var name = document.getElementById('name').value;
            var email = document.getElementById('email').value;
            var message = document.getElementById('message').value;
            $("#loader").css("display","block");
            $.ajax({
                type:       "POST",
                url:        "/send.php",
                cache:      false,<br />
                data:        "name=" + name +"&email="+email+"&message="+message,
                success:    function(html) {
                    $("#loader").fadeOut('fast');
                    $("#submit_button").attr('disabled', 'disabled');
                    $("#contact_form").append('<span class="error" id="send_message">Your message has been sent!<br/>  We will contact you shortly</span>');
                    $("#send_message").fadeIn("slow");
                    setTimeout('$("#send_message").fadeOut("slow");',2250);
                }
            });
        }
return false;
}

When the user clicks the send button, the form triggers the “validate_form()” function.  This function starts by validating each input field.  It starts with the name field which simply detects if the field is empty or not.   Next we move onto the email field which we use a regex string to determine if the field was written in a valid email format.  Finally we check to see if the message field is empty.   As the function detects errors it will display a message over the respective field and halt the script.

Once the form has been validated we use the $.ajax() function to process the data to the php file which sends the message.  The $.ajax() function can be daunting at first so I will explain the settings used.  Starting with the “type” setting, this specifies how we are sending the data to the PHP file.  In this example we are using the POST method, however a GET request could used instead.    The following setting, url, specifies the location of the PHP file we are going to use to send the message.  Next we choose to disable caching as each use of the form will be unique.  We then move onto the data setting, this is where the form data is placed.  As you can see we send the data in the form of 3 variables, an array could also be used.   The last setting determines what to do when the message has successfully been sent.  The “success” setting is only triggered if the message is sent, otherwise the function stops.  Assuming everything goes through correctly, we fade in a message stating the success.  We also disable the submit buttons function to stop from multiple messages being sent at once.

The PHP

Finally we have the PHP code to finish everything off.  In our example we placed this code in the send.php file:

<?php
$name = addslashes($_POST['name']);
$email = "FROM: ".$_POST['email'];
$message = addslashes(nl2br($_POST['message']));
$to = 'info@tobstudios.com';
$message = "Name: ".$name."n".$message;
if ($name != '' && $email !='' && $message != ''){
   if (mail($to, 'Tob Studios Contact Form', $message, $email)){
       return true;
   }else{
       return false;
   }
}
?>

The PHP code is short and to the point, we take the data sent from the $.ajax() function and again validate the information (although in much less detail).  Assuming everything is valid, we then send the message using the PHP “mail” function.

Conclusion

This form albeit simple, offers you a solid foundation to add more complex features such as file uploads and other options.  Remember to put the “enctype=”multipart/form-data” code into your form declaration to process file uploads correctly.  Let us know your thoughts and ideas on how to improve this form in our comments section below.

8 Responses to “Simple Ajax Contact Form”

  1. Simple Ajax Contact Form | Tob Studios

    […] See the rest here: Simple Ajax Contact Form | Tob Studios […]

    Reply
  2. Carol

    Much appreciated for the information and share!

    Reply
  3. Mike

    I actually like this, but there’s a problem. If the user submits the form, what if they need to send another message? It turns out you have to reload the page to make the form work again. Any idea of how to get around that?

    Reply
    • Anonymous

      Thanks for the comment.

      Basically you can fix that issue by removing the $(“#submit_button”).attr(‘disabled’, ‘disabled’); command from the success function. That’s on line 41 of the jQuery code.

      Reply

Leave a Reply