Build Your Own Ajax Contact Form in WordPress

Don’t have much background in PHP, AJAX and Javascript? that’s ok, you can still use this tutorial.

Today I am going to show you how you can build an AJAX Contact Form for your WordPress blog.

Start by creating a PAGE in your WP backend, name the page “contact”. Then in your theme directory create a file with similar contents to your page.php, name the file: page-contact.php . In your Settings->Permalinks, make sure that the “Post name” is selected.

Now open page-contact.php then add the following code: (it should be within the loop)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div id="contact_form">
   
    <div id="result"></div>
   
    <div class="form-group">
        <label for = "name">Name</label>
        <input type="text" name = "name" class = "form-control input-name" placeholder="Enter Your Name" />
    </div>
    <div class="form-group">
        <label for = "email">Email</label>
        <input type="email" name = "email" class = "form-control input-email" placeholder="Enter Your Email" />
    </div> 
    <div class="form-group">
        <label for = "message">Message</label> 
        <textarea name = "message" class = "form-control input-message" rows="4" placeholder="Enter Your Message"></textarea><br />
    </div>
   
    <button class = "btn btn-primary submit">Submit</button>
   
</div>

Just bellow the above code, add the javascript:

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
<script type="text/javascript" >
function cvf_form_validate(element) {
    $('html, body').animate({scrollTop: $(element).offset().top-100}, 150);
    element.effect("highlight", { color: "#F2DEDE" }, 1500);
    element.parent().effect('shake');
}
   
jQuery(document).ready(function($) {

    $('body').on('click', '.submit', function() {
       
        if($('.input-name').val() === '') {
            cvf_form_validate($('.input-name'));
           
        } else if($('.input-email').val() === '') {            
            cvf_form_validate($('.input-email'));
           
        } else if($('.input-message').val() === '') {              
            cvf_form_validate($('.input-message'));
           
        } else {
            var data = {
                'action': 'cvf_send_message',
                'name': $('.input-name').val(),
                'email': $('.input-email').val(),
                'message': $('.input-message').val()
            };
           
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
            $.post(ajaxurl, data, function(response) {
                if(response === 'success'){
                    alert('Message Sent Successfully!');
                    $('.input-name').val(''); $('.input-email').val(''); $('.input-message').val('');
                }
            });
        }
    });
});
</script>

In our code above, we are simply sending the POST request to the admin-ajax.php file of WordPress. It parses your data by looking for the ‘action’ variable which in our case is: ‘cvf_send_message’. The data is passed to the PHP function: ‘wp_ajax_cvf_send_message’. So next step is we need to create the call back function that will handle the AJAX post request.

In your functions.php, add the following code:

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
/**
 * @ Author: Carl Victor Fontanos.
 * @ Class: CVF_Posts
 *
 */

 
add_action('wp_ajax_cvf_send_message', array('CVF_Posts', 'cvf_send_message') );
add_action('wp_ajax_nopriv_cvf_send_message', array('CVF_Posts', 'cvf_send_message') );
add_filter('wp_mail_content_type', array('CVF_Posts', 'cvf_mail_content_type') );

class CVF_Posts {
   
    public static function cvf_send_message() {
       
        if (isset($_POST['message'])) {
           
            $to = get_option('admin_email');
            $headers = 'From: ' . $_POST['name'] . ' <"' . $_POST['email'] . '">';
            $subject = "carlofontanos.com | New Message from " . $_POST['name'];
           
            ob_start();
           
            echo '
                <h2>Message:</h2>'
.
                wpautop($_POST['message']) . '
                <br />
                --
                <p><a href = "'
. home_url() . '">www.carlofontanos.com</a></p>
            '
;
           
            $message = ob_get_contents();
           
            ob_end_clean();

            $mail = wp_mail($to, $subject, $message, $headers);
           
            if($mail){
                echo 'success';
            }
        }
       
        exit();
       
    }
       
    public static function cvf_mail_content_type() {
        return "text/html";
    }
}

In the above code we used ob_start(); , ob_get_contents(); and ob_end_clean(); to allow our email message to read HTML elements instead of printing them as is.

About styling the email message: There is no way you can get your email message to read external styles, so what you can only do is to use inline CSS. Ex:

1
<td style = "background: red; color: white; width: 50%">Text</td>

To learn more about styling emails, I created a separate tutorial: Generate Emails with HTML & CSS in WordPress

The tutorial code should work out of the box. If you encountered any problems, there is comment section bellow where you can post your issues or concerns.



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me