Ajax Contact Form Using jQuery & PHP

In this tutorial we will be creating a simple Ajax based Contact form using jQuery and PHP. Why Ajax? because your visitors don’t have to reload the page in order to send you email, they can simply click send button and the email gets sent instantly before their eyes, so it’s just fantastic, no more page reloads!

Tutorial is pretty basic, you should be able to pull it off if you are bit familiar with HTML, PHP and jQuery.
Have a look at the picture below, this is how our contact form going to look at the end. We will have input fields as shown below, you can add or remove the fields as per your requirements in HTML form.

ajax-contact-form

 

Mark UP

Let’s start by writing HTML for contact page, see HTML code in the box below, we start by adding some input fields, a regular contact form contains Name, Email, Phone and Message fields, you may add other fields like Subject, checkboxes, radio buttons or select-box as per your requirements for the contact form.

<fieldset id="contact_form">
<legend>My Contact Form</legend>
<div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>
    
    <label for="email"><span>Email Address</span>
    <input type="email" name="email" id="email" placeholder="Enter Your Email" />
    </label>
    
    <label for="phone"><span>Phone</span>
    <input type="text" name="phone" id="phone" placeholder="Phone Number" />
    </label>
    
    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>
    
    <label><span>&nbsp;</span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    </label>
</fieldset>

If you look closely, you’ll realize that we didn’t wrap our fields with <FORM> tags here like in a typical HTML form. Since we are going to collect field values using jQuery .val(), we don’t really need a typical HTML form functionality here, all we need is fields and a button to trigger jQuery code which will do the rest.

Form Style

You can style your form with CSS, you can either create a separate CSS or include it within the <head></head> section of your page. I have created a separate CSS for you in downloadable file below, you can just download and play with form style using HTML editor until you are satisfied with the contact form look.

I personally use DevTool in chrome browser and Firebug in Firefox browser, these tools allow me to edit, debug, and monitor CSS, HTML and JavaScript live. If you haven’t used these tools before, you should definitely learn to use them, they are life lifesavers.

#contact_form{ width:300px; padding:20px; border: 1px solid #DDD;border-radius: 5px; font-family: Arial; font-size: 11px; font-weight: bold;color: #666666; background:#FAFAFA; margin-right: auto; margin-left: auto;}
#contact_form legend{font-size: 15px; color: #C9C9C9;}
#contact_form label{display: block; margin-bottom:5px;}
#contact_form label span{float:left; width:100px; color:#666666;}
#contact_form input{height: 25px; border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px; color: #666; width: 180px; font-family: Arial, Helvetica, sans-serif;}
#contact_form textarea{border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px;color: #666; height:100px; width: 180px; font-family: Arial, Helvetica, sans-serif;}
.submit_btn { border: 1px solid #D8D8D8; padding: 5px 15px 5px 15px; color: #8D8D8D; text-shadow: 1px 1px 1px #FFF; border-radius: 3px; background: #F8F8F8;}
.submit_btn:hover { background: #ECECEC;}
.success{ background: #CFFFF5;padding: 10px; margin-bottom: 10px; border: 1px solid #B9ECCE; border-radius: 5px; font-weight: normal; }
.error{ background: #FFDFDF; padding: 10px; margin-bottom: 10px; border: 1px solid #FFCACA; border-radius: 5px; font-weight: normal;}

 jQuery Ajax

Now it’s time to write some jQuery code for the contact page. Before we start, make sure you have included jQuery library within the <HEAD> section of your HTML document, without it jQuery code doesn’t work.

We start with $(document).ready() as suggested by jQuery here.

<!-- include Google hosted jQuery Library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- Start jQuery code -->
<script type="text/javascript">
$(document).ready(function() {
//our jquery code goes here
});
</script>

Right after $(document).ready(), we have $(“#submit_btn”).click(). If you notice the submit button ID in our HTML form above, you will realize that we are actually attaching the click event to the button. When a user clicks the button, the event gets triggered, executing all the code within it.

<!-- include Google hosted jQuery Library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- Start jQuery code -->
<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //collect input field values
        var user_name       = $('input[name=name]').val();  //user name
        var user_email      = $('input[name=email]').val(); //user email
        var user_phone      = $('input[name=phone]').val(); //user phone
        var user_message    = $('textarea[name=message]').val(); //message text
        
        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            //data to be sent to server
            post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message};
            
            //Ajax post data to server
            $.post('contact_me.php', post_data, function(response){  
                
                //load json data from server and output message     
                if(response.type == 'error')
                {
                    output = '<div class="error">'+response.text+'</div>';
                }else{
                
                    output = '<div class="success">'+response.text+'</div>';
                    
                    //reset values in all input fields
                    $('#contact_form input').val(''); 
                    $('#contact_form textarea').val(''); 
                }
                
                $("#result").hide().html(output).slideDown();
            }, 'json');
            
        }
    });
    
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
    
});
</script>

 

The above code is pretty self explanatory, we collect values of fields using val(), then we do simple validation to check empty fields. If everything looks ok, we prepare the data to be sent to the server (contact_me.php), and then we simply send the data using jQuery $.post() method.

One more thing here is that after successful Ajax request, our code expects JSON data from the server, not plain text. You can read more about jQuery Ajax here. Once server returns JSON data, we will grab its message, determine the message type and output it accordingly. The results will be displayed within the div element called #result.

PHP Email

Below is our PHP code for the (contact_me.php), the file is needed to send email to the recipient, as well as respond back to user in the event of success or failure. It receives POST data from the contact page, its good idea to sanitize the data using PHP filter_var(), and then again we server-side validate the variables before we proceed with PHP email. As you can see I have used PHP json_encode() to return JSON encoded data to output success or error messages, which will be grabbed and parsed by jQuery.

<?php
if($_POST)
{
    $to_Email       = "myemail@gmail.com"; //Replace with recipient email address
    $subject        = 'Ah!! My email from Somebody out there...'; //Subject line for emails
    
    
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    
        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error', 
            'text' => 'Request must come from Ajax'
        ));
        
        die($output);
    } 
    
    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
    
    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if(!is_numeric($user_Phone)) //check entered data is numbers
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
        die($output);
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }
    
    //proceed with PHP email.

    /*
    Incase your host only allows emails from local domain, 
    you should un-comment the first line below, and remove the second header line. 
    Of-course you need to enter your own email address here, which exists in your cp.
    */
    //$headers = 'From: your-name@YOUR-DOMAIN.COM' . "\r\n" .
    $headers = 'From: '.$user_Email.'' . "\r\n" . //remove this line if line above this is un-commented
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
        // send mail
    $sentMail = @mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);
    
    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
        die($output);
    }
}
?>

That’s it! we now have a neat looking Ajax based contact form. I hope you can now be able to create your own by taking examples from here, or you can just download the entire code from link below and integrate it on your website right away, please note jQuery may not support old Internet Explorers, good luck!

Please follow and like us:



Leave a Comment

Your email address will not be published. Required fields are marked *