Many premium WordPress templates I have seen are using the plugin Contact Form 7 to offer an Ajax contact form for the template user. This works for most people very well and the user is able to change the contact form without to change any code. For most WordPress websites I have built, there was a single contact form more than enough and most of my customers never change that form on their own. So why using a plugin for a simple feature like a contact form? The new version of this website is based on a premium theme where the contact form was already built using some custom files. I really like the design, but the web form and the function that has to process the form data wasn’t the code quality I was looking for.

Ajax contact formAjax Contact form tutorial

This tutorial is written for the advanced WordPress user, but I’m sure the less experienced user with a little knowledge in PHP, HTML and jQuery can use the tutorial code, too. We use and explain the following features:

  • WordPress Ajax function – I’m using the native WordPress Ajax functionality and jQuery to process the contact form
  • Email address validation – Read more about our previous Mailgun email address validator tutorial
  • Nonce value validation – Read more about securing form submissions in WordPress using nonces

If you don’t like to use this tutorial code, there is also a Ajax Contact Form plugin based on this tutorial!

For this tutorial I use a WordPress short code to create the HTML code for the web form. This is more flexible than using a new template for each WordPress theme.

This shortcode is pretty simple and has no options or parameters. Notice the function wp_nonce_field(), this WordPress function will create the HTML code for the nonce validation we’re using later. The hidden form field with the name “action” is required for the Ajax process, you need to remember that value later. Place this code into your theme’s functions.php file. Let’s continue to the jQuery code, create a file named “contact.js”, paste the code below and save the file into the “js” sub-directory from your WordPress theme directory (create the directory if it doesn’t exists).

Okay, this a lot of code and I will explain the most important parts. There are two jQuery Ajax calls in this script. If you don’t know how this jQuery functions  works, please check their manual, too. If the visitor has clicked the button (#contactbutton), the loading image is fired and the form field values are passed to the variables “message”, “name” and “email”. The following IF statement is a simple test that all three form field values are not empty. If “false” an error message shows up and otherwise the first Ajax function is called. The function has some attributes (I explain the important ones):

  • The value for url points to the Mailgun API (you need a Mailgun account, get one here it’s free)
  • The attribute data is used to send the email address and the public API key (you need to enter your own key) to the Mailgun API endpoint
  • The dataType is set to “jsonp” (note the “p” for parentheses)
  • If the Ajax call to the Mailgun API was successful the function for the attribute success is executed
  • The code for the attribute error is used to show some message if something went wrong.

If the API call was successful we can use an object named data and that is passed to the function. If “data.is_valid” is true, the next Ajax call is executed. If not we get two different messages: For that case that the Mailgun validator has returned a value for “data.did_you_mean”, the script will show a message including a suggestion for a correct email address and otherwise the script shows a generic error message. The second Ajax function is used to post the form data to the WordPress Ajax URL. This is the value “ajax_object.ajax_url” and we define this one later. For the data attribute we use the jQuery “serialize” function to create a data set from our web form form (#contactform). If the Ajax response is successful the web form becomes a reset and we return the message we got inside the response.

Ajax in WordPress

If you use the jQuery Ajax function you need to define a target URL. That was for the Mailgun API call an external URL and for the form data we use an object with the name ajax_object. Now we need to define the values for the object URL.

This custom function will include the “contact.js file into your site’s header. The condition is_page() will allow the code only for a page with the slug “contact”. The function wp_localize_script() creates for the same page the WordPress Ajax URL and our jQuery code will use that value as the target for the form data. The PHP code belongs into your functions.php file. Now we need a function that will email the form data to the WordPress site admin.

First we take a look at the last two rows from this snippet. Do you remember the hidden form tag with the name action? The value is the same as the second part of the hook “wp_ajax_contactform_action” or “wp_ajax_nopriv_contactform_action”. The value “contactform_action” is used to identify that the custom function is called if an Ajax call is done. Why two of them? The second is used for those users are logged in and the first for all others. Okay let’s go back to the first rows from this function. There is another IF statement that is responsible for a check that all none of the $_POST vars is empty. If this check is passed, the function will check the nonce and continues only if the nonce is valid. Now we will filter the $_POST values to remove possible mail header injections. The PHP constant variable PHP_EOL is used to create a new lines (like \n and/or \r). Before you can use the function you need to update code to create a valid FROM mail header. We use an IF statement for the function wp_mail() to check that the mail was send successfully. If yes the variable $status is set to “true” and a friendly message is passed to the variable “$error”. The last rows inside the function will create a JSON string from an array and the response for the Ajax call is done by using a simple “echo”. Add this code to your theme’s functions.php file and you’e done. The tutorial code should work out of the box (don’t forget to change the API key and the FROM mail header), but I’m sure you like to use different or more form fields and maybe other messages. Start your modifications carefully and update always the form field and variable names on all three places: the form shortcode, the contact.js file and the email function. Don’t forget to style the form in your CSS style-sheet! You can download the tutorial code here. If you have questions about this tutorial, please use the comment form below. Thanks for sharing!