This tutorial will cover how to create an Email Form using AJAX (specifically using the Prototype javascript library and the Livevalidation javascript library) and PHP. I will assume you have at least a basic knowledge of HTML, CSS, PHP and Javascript.

Note: The Prototype library is by no means the only Javascript framework that provides simple AJAX functionality. There are many javascript libraries out there that will do the same thing, such as JQuery.

1) Downloads the Libraries

So first of all we are going to need to download two Javascript libraries to create our form.

  • The Prototype library to give us an oh-so-simple AJAX interface and access to the DOM.
  • Livevalidation to help us validate our form.

2) The HTML

Next create a HTML page. I won’t go into great depth in this tutorial with the HTML as I assume if you are reading this you will probably know how to make an HTML page. Now in the <head> section include the two javascript libraries we downloaded.

<script src="prototype.js" type="text/javascript"></script>
<script src="livevalidation.js" type="text/javascript"></script>

Next we want to make our actual email form. In this case we will be asking for normal information, i.e. name, email address, website and a message. This is standard for contact pages on most websites. However it is very easy to change the information you ask for and even use this tutorial for a different kind of form altogether.

<form id="my-form">
	<table>
	<tr><td>Name</td><td><input type="text" id="name" name="name" /></td></tr>
	<tr><td>Email<br /><small>(will never be published)</small></td><td><input type="text" id="email" name="email" /></td></tr>
	<tr><td>Website</td><td><input type="text" id="website" name="website" value="http://" /></td></tr>
	<tr><td valign="top">Message</td><td><textarea cols="40" rows="5" name="message" id="message"></textarea></td></tr>
	<tr><td>&nbsp;</td><td><input type="button" value="Send" onclick="sendRequest();" />
	<input type="button" id="resetbut" name="resetbut" value="Reset" onclick="resetForm();"  /></td></tr>
	</table>
</form>
<br />
<div id="update_div" style="display:none;"></div>

Notice the form doesn’t have an action field or a submit input. This is because we won’t actually be submitting the form like HTML expects us to. Also notice we have a div “update_div” which is initially hidden. This is where we will show updates to tell the user whats going on. The last thing to notice is the “onclick” attribute to the submit button which will call our Javascript function.

3) The Javascript

So this is the fun bit. First of all in the Javascript we want to add the Livevalidation. This is realtively simple. I won’t explain here how Livevalidation works but you can read the documentation on their website. It’s pretty self explanatory.

var name = new LiveValidation( 'name' );
name.add( Validate.Presence );
var email = new LiveValidation( 'email' );
email.add( Validate.Presence );
email.add( Validate.Email );
var message = new LiveValidation( 'message' );
message.add( Validate.Presence );

Next we are going to write our “sendRequest()” method which gets called when we click the “Send” button.

function sendRequest(){
	if(LiveValidation.massValidate( [ name, email, message ] )){
		new Ajax.Request('ajax.php',
		{
			method:'post',
			parameters: $('my-form').serialize(true),
			onLoading: function(){
				$('update_div').show();
				$('update_div').innerHTML = "Sending...";
			},
			onSuccess: function(transport){
				var response = transport.responseText || "No response text";
				$('update_div').innerHTML = response;
			},
			onFailure: function(){ 
				$('update_div').innerHTML = "Something went wrong...";
			}
		});
	}
}

This is where we start using the Prototype Javascript library. So what is happening here?

  1. We use Livevalidation’s massValidate() method to make sure eveything is right.
  2. Prototype’s Ajax.Request method is next up. As you can see using Prototype really makes Ajax functionality a breeze. We define here what file we are requesting (in our case “ajax.php”).
  3. Next up are the options that need to set for our AJAX request to work. For instance we set the method to POST (rather than GET) as you would in a normal HTML form.
  4. The parameters value defines what actual values get passed to the PHP. Prototype comes with a nice method called seralize(). It basically takes all the values in the form, referenced by it’s id, and converts them into the correct format to pass to the PHP. This is very useful when using AJAX forms.
  5. The last thing we do is use three response callbacks that are pre-defined in Prototype. These functions helps us deal with the AJAX request and the information in the response. In this example each method changes the innerHTML of the “update_div” to show either “Loading…”, “Something went wrong…” or the reponse we recieve.

The last thing we want to do is add the Javascript code for the “Reset” button. This isn’t necessary but makes your form a little more user friendly. Also with larger forms this may come in handy.

function resetForm(){
	$('update_div').hide();
	$("update_div").innerHTML = "";
	$("name").value = "";
	$("email").value = "";
	$("website").value = "http://";
	$("message").value = "";
}

Again here we are using Prototype to make access to the DOM really easy. The $(element_id) method is really useful as you can see. We also use the built in hide() method to make hiding the “update_div” much easier.

4) The PHP

Finally we have the PHP page. This is where our AJAX request will be sent. In here we deal with the information and, in this case, use php to send an email. This is much the same as you would do in a normal HTML form. Again this could be any kind of form. So in ajax.php:

<?
@extract($_POST);
$name = stripslashes($name);
$email = stripslashes($email);
$website = stripslashes($website);
$message = stripslashes($message);
if(mail("test@example.com","Email from $name","
$message
 
(From $name, $email, $website)","From: $email")){
	echo "Email Successfully Sent!<br /><br />Name: $name<br />Email: $email<br />Website: $website<br />Message: $message";
}
?>

As you can see here this is just a simple usage of PHP’s mail() function. To find out about more the mail() function at the php.net website. The one thing to notice here is that we “echo” our success message if the message is sent. Why do this? Well this is actually how AJAX responses work. Remember in our Javascript we had these lines:

var response = transport.responseText || "No response text";
$('update_div').innerHTML = response;

The “transport.responseText” is what we are echoing here.

Conclusion

So you know have a fully functioning AJAX email form. Something I haven’t really covered in this tutorial is security. I’m not going into here but remember to always code defensively and NEVER trust user input. Another feature which I haven’t implemented here is having some kind of spam protection. This is highly recommended for all HTML forms. A simple question like “Is the sun hot?” or a captcha usually do the trick.

View the Demo Download the ZIP file

Related Posts

More?

If you enjoyed this post, please consider promoting it.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Design Float
  • Reddit
  • Mixx
  • Technorati

Remeber to subscribe to the feed and get future articles delivered to your feed reader.

If you want to discuss this tutorial or any other thoughts you have then you can do so over on our fourm.

Comments

  1. Nice post dude!
    Thx for the tut..

    ps: ADD your posts to DesignFloat, it would increase your traffic.

  2. Trying to integrate this into a webpage.

    I have tried it but the email doesn’t seem to get sent anywhere.

    I ma a designer, not a coder but I am learning…!

    How do I direct the message at my email address??

  3. In the ajax.php file look for “test@exmaple.com”. Replace this with your own email address.

  4. Comment by sep on January 4, 2009 5:07 pm

    Thanks for this tutorial!

  5. Thanks a lot it work great
    Look at http://www.wemakeweb.de
    Thanks

  6. Comment by Edo on February 24, 2009 4:14 pm

    Not working

  7. @Edo: What part isn’t working?

Leave a Comment

(required)

(required)