User
Password
Remember Me

How to add a jquery/ajax contact form to Wordpress

Did you ever wanted to add a custom contact form to your Wordpress Theme? In this tutorial we will show you step by step how to easily add your own jquery/ajax featured contact form to your Wordpress installation. We will add some default styling which can be adopted and customized by yourself.

demo

1. Adding a page template

Did you ever add a custom page template to one of your Wordpress Themes? No? It is really easy. The code below shows you how to do. We would advise you to copy your template’s page.php file and then copy the code from below and paste it in the content-div of your page.php copy. At the top of your file (name it contact.php f.e.) add the following (Before the get_header and everything else)

<br />
/*<br />
Template Name: Contact Form<br />
*/<br />

This code makes sure, that you can choose the page template, when adding a new page in your wordpress administration area. Now add the following code to your contact.php’s content-div:

</p>
<div class="contact">
<div id="node"></div>
<div id="success">Thank you for leaving a message.</div>
<form name="contact_form" id="contact_me"/>
        <label for="name">Your Name*</label></p>
<input type="text" name="name" value="" />
        <label for="company">Your Company</label></p>
<input type="text" name="company" value="" />
        <label for="telephone">Telephone Number</label></p>
<input type="text" name="telephone" value="" />
        <label for="mail">Your E-Mail*</label></p>
<input type="text" name="mail" value="" />
        <label for="message">Your Message*</label><br />
        <textarea name="message"></textarea></p>
<input type="submit" value="submit" />
    </form>
</div>
<p>

Allright! Now save your file and upload it to your wordpress-theme directory. After that, add a new page and choose “Contact Form” as your page template!

2. Adding the CSS to your syle.css

Now that we did the structuring, we need to style the html. To do so, copy the code from below and paste it in your theme’s style.css. Of course you can customize the whole CSS to adopt your theme’s look!

<br />
.contact {<br />
float: left;<br />
width: 100%;<br />
}<br />
.contact label {<br />
float: left;<br />
width: 150px;<br />
margin-bottom: 10px;<br />
clear: both;<br />
}</p>
<p>.contact input {<br />
float: left;<br />
width: 180px;<br />
border: 1px solid #CCC;<br />
padding: 3px;<br />
margin-bottom: 10px;<br />
}<br />
.contact textarea {<br />
float: left;<br />
width: 250px;<br />
height: 100px;<br />
border: 1px solid #CCC;<br />
}<br />
.contact #node {<br />
float: left;<br />
width: 360px;<br />
display: none;<br />
background-color: #CC5553;<br />
padding: 5px;<br />
color: #FFF;<br />
border: 1px solid #9B413F;<br />
margin-bottom: 10px;<br />
}<br />
.contact #success {<br />
float: left;<br />
width: 360px;<br />
background-color: #8ACC39;<br />
color: #FFF;<br />
padding: 5px;<br />
border: 1px solid #6DA32C;<br />
display: none;<br />
margin-bottom: 10px;<br />
}<br />
.contact input[type=submit] {<br />
float: left;<br />
width: auto;<br />
padding: 5px 20px;<br />
background-color: #FFF;<br />
border: 1px solid #CCC;<br />
text-align: center;<br />
margin-top: 10px;<br />
cursor: pointer;<br />
clear: both;<br />
margin-left: 150px;<br />
}<br />

3. Adding the Javascript/Ajax Function

Now we will have to add some jQuery Code to your theme, to make the contact form work! You will need to add the following code to a new file (we name it contact.js).

<br />
jQuery(document).ready(function($) {<br />
       jQuery("#contact_me").submit(function() {<br />
	var str = jQuery(this).serialize();<br />
	jQuery.ajax({<br />
	    type: "POST",<br />
	    url: "/wp-admin/admin-ajax.php",<br />
	    data: 'action=contact_form&'+str,<br />
	    success: function(msg) {<br />
		jQuery("#node").ajaxComplete(function(event, request, settings){<br />
                if(msg == 'sent') {<br />
                    jQuery(".contact #node").hide();<br />
		    jQuery(".contact #success").fadeIn("slow");<br />
                }<br />
                else {<br />
                    result = msg;<br />
                    jQuery(".contact #node").html(result);<br />
		    jQuery(".contact #node").fadeIn("slow");<br />
		}<br />
		});<br />
	    }<br />
	});<br />
	return false;<br />
    });<br />
});<br />

Now that we have the new file “contact.js”, upload it to your theme directory.

4. Handling the Ajax Post-Values

Now that we have the javascript, we will need to handle the values which are sent by the form. Now it’s a little tricky because we are using Wordpress-built-in Ajax function. Open up your theme’s functions.php (if doesn’t exist add a new file) and paste the following code:

<br />
add_action('init', 'add_contact_script');<br />
function add_contact_script() {<br />
    wp_register_script('contact', get_bloginfo('template_directory') . '/contact.js', array('jquery'), '1.0' );<br />
    wp_enqueue_script('contact');<br />
}<br />
function ajax_contact() {<br />
    if(!empty($_POST)) {<br />
	$name = $_POST['name'];<br />
	$company = $_POST['company'];<br />
	$telephone = $_POST['telephone'];<br />
	$mail = $_POST['mail'];<br />
	$admin_mail = get_bloginfo('admin_email');<br />
	$msg = $_POST['message'];<br />
	$error = "";<br />
	if(!$name) {<br />
	    $error .= "Please tell us your name<br/>";<br />
	}<br />
	if(!$mail) {<br />
	    $error .= "Please tell us your E-Mail address<br/>";<br />
	}<br />
	if(!$msg) {<br />
	    $error .= "Please add a message";<br />
	}<br />
	if(empty($error)) {<br />
	    $subject = "New contact form received";<br />
	    $message = "You've received a new contact form. \n\n<br />
			Name: ".$name."\n<br />
			Company: ".$company."\n<br />
			Telephone: ".$telephone."\n<br />
			Mail: ".$mail."\n<br />
			Message: ".$msg."\n";<br />
	    $mail = mail($admin_mail, $subject, $message,<br />
	    "From: ".$name." <".$mail.">rn"<br />
	    ."Reply-To: ".$mail."rn"<br />
	    ."X-Mailer: PHP/" . phpversion());<br />
	    if($mail) {<br />
		echo "sent";<br />
	    }<br />
	    die();<br />
	} else {<br />
	    echo $error;<br />
	    die();<br />
	}<br />
    }<br />
}<br />
add_action('wp_ajax_nopriv_contact_form', 'ajax_contact');<br />

Make sure that your theme has already included the jQuery Framework, otherwise it won’t work!

Now that you have all the files uploaded and updated you can have a look at your new contact page and try to write a new contact request. Hope this tutorial was helpful for you! Build your own jquery ajax contact form in Wordpress in just 4 steps!

10 Comments to “How to add a jquery/ajax contact form to Wordpress”
  1. Amit says:

    Hey buddy,
    can u please tell me how can i add styles to sidebars like u have used css for “Pages” sidebar in demo page ?

  2. Mo says:

    heya mate,

    Thanks for sharing this. I have been trying to apply this to my own sites but somehow i cant get it to work. I’m not sure if it supposed to be like this but if i copy/paste everything into my theme it doesnt work at all.

    When i change the url: “/wp-admin/admin-ajax.php” to url: “wp-admin/admin-ajax.php” it works but not the way it should be working. When i do change it and press the submit button the error div shows up but only showing a 0. I have been trying to read through the codex but somehow i just cant find out what the problem is, maybe you have an idea what it might be?

    thnx

    • Mo says:

      ok now all of a sudden it works….how frustrating this is because i have no idea what made it work all of a sudden.

      After putting all the code next to eachother, the only things i have changed is the url as stated before and adding “add_action(‘wp_ajax_contact_form’, ‘ajax_contact’);” to the functions.php. apart from that i havent changed anything else.

      Thanks again for the tutorial.

    • admin says:

      The problem is, that

      add_action(‘wp_ajax_nopriv_contact_form’, ‘ajax_contact’);

      will only work for users, who are not logged in within Wordpress, otherwise you will get an 0 as return value. (no_priv in add_action).

      Cheers

  3. Connie says:

    I think I followed all of your directions correctly but when I make the final change to the functions php something goes wrong. I end up with text at the top of my wp admin page and the same text appears on the contact page of my website. Is there something I need to adjust in the code in order to make it work properly? I’m using wp-creativix, does that theme include jquery framework?

  4. Connie says:

    Okay, I guess I must’ve gone wrong somewhere in step 3… I’m not sure how though. Can you please help me out on this? I really love this theme!

  5. Steve says:

    Thanks for this. I’ve been looking for a nice way to build in a simple contact form in a WordPress template without requiring a plugin. I REALLY like that it transparently inserts the admin_email so the user doesn’t have to manually muck with the code to insert their email address. My only concern is there doesn’t appear to be any attention given to sanitizing the input to thwart any malicious code injection attempts. Do you have any recommendations for how to tighten up the security of this form? Thanks for this very helpful post.

  6. carson says:

    Connie: Make sure that your theme has already included the jQuery Framework, otherwise it won’t work!

    Steve: There is a nice plugin “WP Captcha Free” that will Block comment spam without the hassle of captcha. It should protect your contact form submissions too. Let me know if it doesn’t please. It has a sophisticated algorithm that has protected my site and blocks out all the spam. : ) Search WP site for free plugin name.

  7. This was exactly what I needed. Thanks a lot for taking the time to walk step by step through an ajax contact form.

  8. Dharam says:

    Cool! after hitting the wall with my head for 4 hours, this step-by-step guide worked like a charm and “chain-able” as well (to do extra validation).Thanks

Leave a Reply

(required)

(required)