Add custom fields to the AJAX Contact Form

by .

In a burst of WordPress fever we decided to write another blog post to help all of our ThemeForest / CodeCanyon customers with our ever popular AJAX Contact Form.

In this example we’re going to add a new simple text field (Your Height) which we want all users to fill in (a required, validated field).

Step One

Firstly, backup backup and backup again, once you’ve done that we need to edit our HTML to include our new field, we’re going to add this one under the ‘Your Name’ field.

In the included index.html file find the following lines..

<input id="name" name="name" size="30" type="text" />

Below it we’re going to insert our new text field called ‘height’..

<label for="height"><span class="required">*</span> Your Height (cm)</label>
<input id="height" name="height" size="30" type="text" />

Now save and close index.html, that’s the first step out of the way.

Step Two

This is an often overlooked though most important step of this tutorial.

We’re going to edit the Javascript handler (the AJAX part) of the contact form.

In the js/jquery.jigowatt.js file find the following line..

name: $('#name').val(),

For this example add the following code immediately below.. (please note the comma , after the line – this is important)

height: $('#height').val(),

Once done the section of the code should look like this..

name: $('#name').val(),
height: $('#height').val(),
email: $('#email').val(),

Save and close jquery.jigowatt.js, that’s the second step done!

Step Three

The third and final step! We’re going to add our new field to the PHP form handler. This will validate it’s contents and put it into the e-mail.

In contact.php find the following line (aprox line 5)

$name = $_POST['name'];

Add the following code immediately below..

$height = $_POST['height'];

In contact.php find the following lines (aprox line 13)

echo '<div class="error_message">Attention! You must enter your name.</div>';

Add the following code immediately below..

} else if(trim($height) == '') {
echo '<div class="error_message">Attention! Please enter a your height.</div>';
} else if(!is_numeric($height)) {
echo '<div class="error_message">Attention! Your height can only contain digits.</div>';

This piece of code checks that the user has firstly entered a value, and the further checks that they have only entered a numeric value. The only variables within this are $height and the error message you want to display if it finds a discrepancy.

And finally, place our validated variable into the e-mail.

Find the following (aprox line 70)

You have been contacted by $name with regards to $subject

Replace this with the following (notice the sentence change to include our new $height variable)

You have been contacted by $name who is $height cm tall with regards to $subject

And that’s it, you’ve just added a new field to your AJAX Contact Form! Upload the changed files and give it a test.