jQuery Contact form for your website

These days it’s very hard to prevent your e-mail box against spam if you like to get in touch with your website’s visitors. If you place some e-mail address on your website or even a regular contact form makes you possibly a victim of spambots. There are many ways to protect your inbox against spam, spam filters and protections on your contact form page will help for sure.

n this tutorial we show how to create a modern contact form that is linked by a simple text link and opens in a fancy Lightbox where all form handling, including reCAPTCHA validations, are processed by PHP and the jQuery Ajax function. After the form submission was successful we are using the PHP Class script PHPMailer to send the message via SMTP.

Previous Tutorials we have used for this application

Create custom reCAPTCHA images using their API
We use the reCAPTCHA API to create a user validation image to protect the form against spam attacks.

Sending e-mails via SMTP with PHPmailer and Gmail
We send e-mail messages using the PHPmailer script via SMTP, the mail function from this previous tutorial is the base for this tutorial as well.

Next we use the Ajax function from jQuery to send the form variables to our PHP e-mail script. This tutorial describes how-to to use all the functions in one application, please check the other tutorials if you need more information. We will not explain the code for PHPMailer and reCAPTCHA in this tutorial. You need an API key for the reCAPTCHA service.

Thickbox jQuery Plugin

We use the Thickbox plugin for this tutorial because we think that this plugin is easy to use and very flexible. If you visit the Thickbox website you will notice some “warning” from the developer, he says that he doesn’t continue the development. If you don’t like to use the Thickbox plugin you need to use one of the other Lightbox plugins available on the Internet. Since the application is not related to the Thickbox plugin, it should be easy to use that code with most other Lightbox scripts as well.

Contact form

This page is used to collect the users input, will validate the input on the client side and will post the data to the PHP e-mail script. Create a file with this code and call it contact-form.html



<html>
<head>
<title>Contact form</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script>
<script type="text/javascript">

Next we have the jQuery script block for the form validations, Ajax form submission and the code to request the challenge image from the reCAPTCHA API.

After the document is loaded the reCAPTCHA images is added. If the user has clicked the button #submit_button the Ajax function is called with:

* Options like the PHP e-mail script,
* the form data,
* the data type JSON,
* a pre-submit handler for the form field validations
* and a success handler that put the response into the #output container.

$(document).ready(function() {
var RecaptchaOptions = { theme : 'custom' };
Recaptcha.create('your public key', 'recaptcha_image', RecaptchaOptions);
Recaptcha.focus_response_field();
$('#submit_button').click(function() {
$.ajax({
type: 'POST',
url: 'email.php',
data: $('form#myform').serialize(),
dataType: 'json',
beforeSend: function() {
var resp_field = $('#recaptcha_response_field').val();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
if (!resp_field[0] || !name[0] || !email[0] || !message[0]) {
$('#output').html('All fields are required');
return false;
}
emailpat = /^([a-z0-9])+([.a-z0-9_-])*@([a-z0-9])+(.[a-z0-9_-]+)+$/i;
if (!emailpat.test(email)) {
$('#output').html('The e-mail address is not valid.');
return false;
}
},
success: function(response) {
if (response.status == 'success') {
$('#formcont').html();
}
$('#output').html(response.errmessage);
}
});
});
});

The form has just a few fields for name, e-mail address and message. Note the container with the ID recaptcha_image, this DIV element holds the reCAPTCHA challenge image

</script>
</head>
<body>
<h1>Contact form</h1>
<div id="formcont">
<form id="myform">
<p>
<label for="naam">Name:</label>
<input type="text" name="name" id="name" size="30" />
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" size="30" />
</p>
<p>
<label for="message">Message:</label>
<textarea rows="5" cols="30" name="message" id="message"></textarea>
</p>
<div id="recaptcha_image"></div>
<p>
<input type="text" name="recaptcha_response_field" id="recaptcha_response_field" size="20" />
<input type="button" value="Submit" id="submit_button" />
</p>
</form>
</div>
<div id="output"></div>
</body>
</html>

PHP e-mail script

So far the client side code, now we need an email script called email.php with following functions:

* One that validates the submitted reCAPTCHA answer against the API,
* has some basic validations on the server side (empty fields)
* sends the e-mail message using the PHPmailer class,
* and responds (echo) the message in JSON format.


<?php
require_once('PHPMailer/class.phpmailer.php');
$resp['status'] = 'error';
$resp['errmessage'] = '';

if (!empty($_POST)) {
if (!empty($_POST['email']) && !empty($_POST['message']) && !empty($_POST['name']) && !empty($_POST['recaptcha_response_field'])) {
$answer = trim(stripslashes($_POST['recaptcha_response_field']));
$postData['challenge'] = $_POST['recaptcha_challenge_field'];
$postData['response'] = urlencode($answer);
$postData['remoteip'] = $_SERVER['REMOTE_ADDR'];
$postData['privatekey'] = 'your private key';
$ch = curl_init("http://api-verify.recaptcha.net/verify");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response = explode(PHP_EOL, $data);
if ($response[0] == 'true') {
$mail = new PHPMailer();
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'you at gmail dot com';
$mail->Password = 'your gmail password';
$mail->SetFrom('you@website.com');
$mail->Body = 'Name: '.$_POST['name'] . PHP_EOL .
'E-mail: ' . $_POST['email'] . PHP_EOL . PHP_EOL .
'Message:' . PHP_EOL . $_POST['message'];
$mail->Subject = 'Some message from your site';
$mail->AddAddress('Igetthe@mail.com');
if (!$mail->Send()) {
$resp['errmessage'] = 'Mail error: '.$mail->ErrorInfo;
$resp['status'] = 'success';
} else {
$resp['errmessage'] = 'Message submitted succesfully!';
}
} else {
if ($response[1] == 'incorrect-captcha-sol') {
$resp['errmessage'] = 'The entered text from the Captcha image is wrong.';
} else {
$resp['errmessage'] = 'Can't validate the Captcha image.';
}
}
} else {
$resp['errmessage'] = 'Missing required fields!';
}
}
echo json_encode($resp);
?>

How-to use it on your website?

if you have finished both files you can use them on your site, upload the two created files, the jQuery library, the Thickbox plugin files and the PHPmailer class (if you don’t have those files on your server). Double check all the paths and add the jQuery library and the Thickbox plugin files to the page header from that page, where you like to place one or more Contact links:


<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="thickbox.js"></script>
<link href="thickbox.css" rel="stylesheet" type="text/css" />

You don’t need to add more jQuery code because the code is already included in the Thickbox plugin file. Use the following code for each link:

<a href="contact-form.html?TB_iframe=true&height=480&width=640" class="thickbox">Contact</a>

That’s all, if you have any questions please post them below. At the moment there is no demo but you can download the example code here.

Post a Comment

Previous Post Next Post