PHP AJAX Contact Form

In a previous post I showed you how JQuery’s load function worked, but I only showed you how to use the first parameter which was the url, this first parameter allowed you to load a static page. In this post I will show you how to send data to that url you load, this means that the contents of that page you load will depend on the data you send. We are going to need three files for this tutorial, an html file for the form, a javascript file for JQuery and a PHP file to send the email. The three files should be saved in the same directory.

Let’s take a look at the contents of the html file inside the <body> tag.

<form>
<label>email</label>
<p>
<input type="text" id="email" />
</p>
<label>Message</label>
<textarea id="message">

</textarea>
<input type="submit" value="send" />
</form>
<div id="response">

</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="sender.js" />

As you can see I have created a form without an action or method, an email field with an id "email" and a textarea with id "message", and a division with an id "response" which is where we will see the response from our PHP file. I have also loaded JQuery from the Google APIs and put a script linking to our javascript file which we will call "sender".

Let’s take a look at the contents of this file.

Like always we wait until the document has finished loading to continue.

$(document).ready(function()
{
 // rest of code will go here
});

Now let’s add the good stuff.

$(document).ready(function()
{
	$("form").submit(function()
	{
	
	return false;
	});
});

JQuery has an even called "submit" that is used for forms, it works the same way as Javascript’s "onsubmit", this means that if you return "true" the form will submit, or be sent to the "action" which we did not specify and for that reason we will always return a "false" since we are going to be submitting the form with AJAX.

Let’s continue.

$(document).ready(function()
{
	$("form").submit(function()
	{
		var sendersEmail=$("#email").val();
		var sendersMessage=$("#message").val();
	return false;
	});
});

From the name "val()" you might guess what this function does, that’s right, it returns the value of the selector you prepend to it. This line $("#message").val() is the equivalent of document.getElementById(“message”).value .

Now that we have the values that the user entered we can continue.

$(document).ready(function()
{
	$("form").submit(function()
	{
		var sendersEmail=$("#email").val();
		var sendersMessage=$("#message").val();
		$("#response").load("sendmail.php",{email:sendersEmail,message:sendersMessage});
	return false;
	});
});

This time we will be needing load’s second parameter which is a POST array, the first parameter as you can see is the PHP script we will be using to send send the email. To specify a second parameter, like you do in other languages, you use a comma followed by the parameter.

Let me break down the second parameter. This parameter consists of two curly brackets, opening { and closing }, inside these brackets you put the keys of the array and its values. The syntax for the array is the following.

A key followed by " : " followed by the value.

This becomes

key:value

If you have more then two keys you separate each set of key and value with a coma, like this.

key:value, key2:value2

With our line

{email:sendersEmail,message:sendersMessage}

We will make two PHP POST keys each with it’s corresponding value.

$_POST['email'];
// and
$_POST['message'];

Now let’s do the PHP script ( sendmail.php ). I will be using the Zend email script from a previous post but you can PHP’s mail function.

The way this works is that whatever we echo in our sendmail.php file will be sent to the "response" division in our html form.

// get mail class
require_once 'Zend/Mail.php';
$mail=new Zend_Mail();
// get validator class
require_once 'Zend/Validate/EmailAddress.php';
$validator=new Zend_Validate_EmailAddress();
// get user info
// check email
if($validator->isValid($_POST['email']))
{
// valid email

	// text only option
	$mail->setBodyText(strip_tags($_POST['message']));
	// html option
	$mail->setBodyHtml($_POST['message']);
	$mail->setFrom($_POST['email'],"WebHole");
	$mail->addTo('miguel@webhole.net','Miguel');
	$mail->setSubject('Contact Form');
	// send email
	$mail->send();
	// 
	echo 'Your message was sent.';
}
else
{
// invalid email

	foreach($validator->getMessages() as $errorMessage)
	{
		echo "$errorMessage<br/>";
	}

}

Try the demo at AJAX Contact Form Sample.