Simple 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 later add-remove other fields as per requirements of your HTML form.
contact-form-example-1

Mark UP

Let’s start coding our contact page, we start by adding some input fields, you can review our code below. A regular contact page contains name, email, phone and message fields, you may add other fields like check-boxes, radio buttons and select-boxes as per your requirements for the contact form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div class="form-style" id="contact_form">
    <div class="form-style-heading">Please Contact Us</div>
    <div id="contact_results"></div>
    <div id="contact_body">
        <label><span>Name <span class="required">*</span></span>
            <input type="text" name="name" id="name" required="true" class="input-field"/>
        </label>
        <label><span>Email <span class="required">*</span></span>
            <input type="email" name="email" required="true" class="input-field"/>
        </label>
        <label><span>Phone</span>
            <input type="text" name="phone1" maxlength="4" placeholder="+91"  required="true" class="tel-number-field"/>&mdash;<input type="text" name="phone2" maxlength="15"  required="true" class="tel-number-field long" />
        </label>
            <label for="subject"><span>Regarding</span>
            <select name="subject" class="select-field">
            <option value="General Question">General Question</option>
            <option value="Advertise">Advertisement</option>
            <option value="Partnership">Partnership Oppertunity</option>
            </select>
        </label>
        <label for="field5"><span>Message <span class="required">*</span></span>
            <textarea name="message" id="message" class="textarea-field" required="true"></textarea>
        </label>
        <label>
            <span>&nbsp;</span><input type="submit" id="submit_btn" value="Submit" />
        </label>
    </div>
</div>

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 some fields and a button to trigger jQuery code which will do the rest.

Form Style

You can style your HTML form with CSS, you can either create a separate CSS or include the code within the <head></head> section of your page. 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 in realtime. If you haven’t used these tools before, you should definitely learn to use them, they are lifesavers.

For this example, I’ve borrowed a HTML contact form layout from my other post here, which is included 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.

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.

1
2
3
4
5
6
7
8
9
<!-- 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!-- 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() {
       
        var proceed = true;
        //simple validation at client's end
        //loop through each field and we simply change border color to red for invalid fields      
        $("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
            $(this).css('border-color','');
            if(!$.trim($(this).val())){ //if this field is empty
                $(this).css('border-color','red'); //change border color to red  
                proceed = false; //set do not proceed flag
            }
            //check invalid email
            var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
            if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
                $(this).css('border-color','red'); //change border color to red  
                proceed = false; //set do not proceed flag             
            }  
        });
       
        if(proceed) //everything looks good! proceed...
        {
            //get input field values data to be sent to server
            post_data = {
                'user_name'     : $('input[name=name]').val(),
                'user_email'    : $('input[name=email]').val(),
                'country_code'  : $('input[name=phone1]').val(),
                'phone_number'  : $('input[name=phone2]').val(),
                'subject'       : $('select[name=subject]').val(),
                'msg'           : $('textarea[name=message]').val()
            };
           
            //Ajax post data to server
            $.post('contact_me.php', post_data, function(response){  
                if(response.type == 'error'){ //load json data from server and output message    
                    output = '<div class="error">'+response.text+'</div>';
                }else{
                    output = '<div class="success">'+response.text+'</div>';
                    //reset values in all input fields
                    $("#contact_form  input[required=true], #contact_form textarea[required=true]").val('');
                    $("#contact_form #contact_body").slideUp(); //hide form after success
                }
                $("#contact_form #contact_results").hide().html(output).slideDown();
            }, 'json');
        }
    });
   
    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form  input[required=true], #contact_form textarea[required=true]").keyup(function() {
        $(this).css('border-color','');
        $("#contact_results").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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
if($_POST)
{
    $to_email       = "myemail@gmail.com"; //Recipient email, Replace with own email here
    $from_email     = 'noreply@your_domain.com'; //from mail, it is mandatory with some hosts and without it mail might endup in spam.
   
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
       
        $output = json_encode(array( //create JSON data
            'type'=>'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    }
   
    //Sanitize input data using PHP filter_var().
    $user_name      = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
    $user_email     = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
    $country_code   = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
    $phone_number   = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
    $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
    $message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
   
    //additional php validation
    if(strlen($user_name)<4){ // If length is less than 4 it will output JSON 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(!filter_var($country_code, FILTER_VALIDATE_INT)){ //check for valid numbers in country code field
        $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in country code'));
        die($output);
    }
    if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
        $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
        die($output);
    }
    if(strlen($subject)<3){ //check emtpy subject
        $output = json_encode(array('type'=>'error', 'text' => 'Subject is required'));
        die($output);
    }
    if(strlen($message)<3){ //check emtpy message
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }
   
    //email body
    $message_body = $message."\r\n\r\n-".$user_name."\r\nEmail : ".$user_email."\r\nPhone Number : (".$country_code.") ". $phone_number ;
   
    //proceed with PHP email.
    $headers = 'From: '. $from_email .'' . "\r\n" .
    'Reply-To: '.$user_email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
   
    $send_mail = mail($to_email, $subject, $message_body, $headers);
   
    if(!$send_mail)
    {
        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
        $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!

Next Ajax Contact Form with an Attachment (jQuery & PHP).

Download Demo

  1. Just a question (question message type disabled) re the php, why are you checking if it’s a post request – is it because you’re afraid of reaching the URL size limit?

     Reply
  2. All mail from the contact form is sent as SPAM. Does anyone have a solution to this?

     Reply
    • Try adding in header:

      1
      From:noreply@your_domanin_email.com

      I’ve modified the PHP part, you can copy and try again.

  3. what about checkbox feature?

    I’m looking to add four checkboxes to this form.

    By the way, great form! works!

     Reply
  4. Thank you very much of this information is very useful for beginners like me Blogger

     Reply
  5. Thank you, nice work! How can I insert a google recaptcha?

     Reply
  6. Use latest jquery to output the error message, not 1.11.1.

     Reply
  7. Great & Helpful Tutorial. So easy to understand and use, Thanks for sharing with us.
    I used SMTP and it’s woring fine.

     Reply
  8. Great Post, I just want to point out to those stuck: use event.preventDefault() at the top of the function.
    Also the #result should be changed to #contact_results. Otherwise awesome

     Reply
  9. Hello,
    I use this script. But mail is going to spam..

    Any suggestion to me.

     Reply
  10. Dude. Thank you for all of this. you deserve a lot of success..

     Reply
  11. YOU ARE A STAR! JUST WHAT I NEEDED!

     Reply
  12. If anyone is looking to add several email options to this form, check out this solution on stack exchange: http://stackoverflow.com/questions/32215197/ajax-contact-form-with-dropdown-select-where-email-is-sent

     Reply
  13. On “index.php”, change “$(“#result”).slideUp();” to “$(“#contact_results”).slideUp();” to fix the slideUp property :) this tutorial is fantastic! Thanks!

     Reply
  14. Has anyone had success using Autofill with this form? Everything works great, thanks for this download, only issue is Autofill doesn’t populate the fields

     Reply
Message Type : Question Comment ?
  • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
  • Comment : Short comments and questions.