Getting started with the browser side.

First, download the jQuery library and form plugin and then let’s start creating our HTML form. Keep them all in the same folder for now. We’ll want to first call both javascript files, let’s do that with:

  1. <head>
  2. <title>Ajax Form v1 – Demo</title>
  3. <script type=“text/javascript” src=“jquery-latest.pack.js”></script>
  4. <script type=“text/javascript” src=“jquery.form.js”></script>
  5. </head>

That’s a great start, but we need to make the form before we can customize our javascript to fit the form. Here is a sample form to get us started:

  1. <html>
  2. <form id=“contactForm” action=“sendmailexample.php” method=“post”>
  3. <ul>
  4. <li><label for=“name”>Name:</label><input id=“name” name=“name” type=“text” /></li>
  5. <li><label for=“email”>Email:</label><input id=“email” name=“email” type=“text” /></li>
  6. <li><label for=“tele”>Telephone:</label><input id=“tele” name=“tele” type=“text” /></li>
  7. <li class=“special”><label for=“last”>Don’t fill this in:</label><input id=“last” name=“last” type=“text” /></li>
  8. <li><label for=“message”>Message:</label><textarea rows=“5″ name=“message”></textarea></li>
  9. <li><input type=“submit” value=“Send Message” /></li>
  10. </ul>
  11. </form>
  12. </html>

We have several fields in this form, one for a name, email, telephone number and message. The field marked “last” and “Don’t fill this in:” is the honey pot! The idea is that this will be hidden with CSS with the a line like this:

  1. li.special {
  2. display:none;
  3. }

This should keep humans from entering any value into the field. If a value is entered (by a bot), then the PHP script will recognize this and won’t send out an email.
Now that we have our form it’s time to customize that javascript! Go back the the head of your email:

  1. <script type=“text/javascript” src=“jquery-latest.pack.js”></script>
  2. <script type=“text/javascript” src=“jquery.form.js”></script>
  3. <script type=“text/javascript”>
  4. $(document).ready(function() {
  5. var options = {
  6. target:        ’#alert’,
  7. };
  8. $(‘#contactForm’).ajaxForm(options);
  9. });
  10. $.fn.clearForm = function() {
  11. return this.each(function() {
  12. var type = this.type, tag = this.tagName.toLowerCase();
  13. if (tag == ‘form’)
  14. return $(‘:input’,this).clearForm();
  15. if (type == ‘text’ || type == ‘password’ || tag == ‘textarea’)
  16. this.value = ”;
  17. else if (type == ‘checkbox’ || type == ‘radio’)
  18. this.checked = false;
  19. else if (tag == ‘select’)
  20. this.selectedIndex = -1;
  21. });
  22. };
  23. </script>

Now we have lots more code to talk about! The first bit simply says that the target div for updating dynamically with the echoed stuff from php is “#alert”. The last little bit says that “#contactForm” is the target of the submit! Check it our here:

  1. $(document).ready(function() {
  2. var options = {
  3. target:        ‘#alert’,
  4. };
  5. $(‘#contactForm’).ajaxForm(options);
  6. });

Now the next little function simply clears all of the fields on the form, helping reduce an accidental double click of the submit button. It will be called via a PHP echo after the submit button is clicked:

  1. $.fn.clearForm = function() {
  2. return this.each(function() {
  3. var type = this.type, tag = this.tagName.toLowerCase();
  4. if (tag == ‘form’)
  5. return $(‘:input’,this).clearForm();
  6. if (type == ‘text’ || type == ‘password’ || tag == ‘textarea’)
  7. this.value = ;
  8. else if (type == ‘checkbox’ || type == ‘radio’)
  9. this.checked = false;
  10. else if (tag == ‘select’)
  11. this.selectedIndex = -1;
  12. });
  13. };

That should pretty much do it for HTML side, minus the CSS needed to format it. Make sure to download the demo file here to get all the files and full code. Time to get into the meat of the project and do the PHP!

Getting started with the server side.

There is quite a bit of PHP that will be require to do all this! So let’s put it together in steps, let’s first start by making a function to sanitize the variables for any dangerous characters. We’ll use it later in when we are ready to send the email.

  1. function clean_var($variable) {
  2. $variable = strip_tags(stripslashes(trim(rtrim($variable))));
  3. return $variable;
  4. }

Now we’ll want to check the “last” variable (the honeypot), if it isn’t empty, we’ll skip the mail function and echo a message:

  1. if ( empty($_REQUEST['last']) ) {
  2. //rest of code will go here!
  3. } else {
  4. echo “<script>$(\”.message\”).hide(\”slow\”).show(\”slow\”); </script>”;
  5. echo $honeypot;
  6. }

Assuming the honeypot is empty, we now need to check the variables to see if they are formatted correctly. We’ll do that by checking if their empty and if not, their format. If they fail either test, we’ll return an appropriate error message and flip a variable telling the server to send the error message instead of sending the email to us! This is how we’ll do that for the name:

  1. if ( empty($_REQUEST['name']) ) { //check if its empty
  2. $pass = 1; //flip the variable, send an error message!
  3. $alert .= “<li>” . $emptyname . “</li>”; //this is the customized error message
  4. } elseif ( ereg( “[][{}()*+?.\\^$|]“, $_REQUEST['name'] ) ) { //check if it has any bad characters
  5. $pass = 1; //flip the variable, send an error message!
  6. $alert .= “<li>” . $alertname . “</li>”; //this is another, different customized error message
  7. }

Now a similar format is followed for the rest of the variables, with different validation checks:

  1. if ( empty($_REQUEST['name']) ) {
  2. $pass = 1;
  3. $alert .= “<li>” . $emptyname . “</li>”;
  4. } elseif ( ereg( “[][{}()*+?.\\^$|]“, $_REQUEST['name'] ) ) {
  5. $pass = 1;
  6. $alert .= “<li>” . $alertname . “</li>”;
  7. }
  8. if ( empty($_REQUEST['email']) ) {
  9. $pass = 1;
  10. $alert .= “<li>” . $emptyemail . “</li>”;
  11. } elseif ( !eregi(“^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$”, $_REQUEST['email']) ) {
  12. $pass = 1;
  13. $alert .= “<li>” . $alertemail . “</li>”;
  14. }
  15. if ( empty($_REQUEST['tele']) ) {
  16. $pass = 1;
  17. $alert .= “<li>” . $emptytele . “</li>”;
  18. } elseif ( !ereg( \(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}”, $_REQUEST['tele'] ) ) {
  19. $pass = 1;
  20. $alert .= “<li>” . $alerttele . “</li>”;
  21. }
  22. if ( empty($_REQUEST['message']) ) {
  23. $pass = 1;
  24. $alert .= “<li>” . $emptymessage . “</li>”;
  25. } elseif ( ereg( “[][{}()*+?\\^$|]“, $_REQUEST['message'] ) ) {
  26. $pass = 1;
  27. $alert .= “<li>” . $alertmessage . “</li>”;
  28. }

I think you get the idea! Each error message is encapsulated in a list tag and it appended to the $alert variable. By the end of the run, $alert should contain a string of all the appropriate (if any) error messages which we can then relay to the user. We do that by checking to see if the $pass variable has flipped:

  1. if ( $pass==1 ) {
  2. echo “<script>$(\”.message\”).hide(\”slow\”).show(\”slow\”); </script>”; //js for the error message effect
  3. echo “<strong>” . $errormessage . “</strong>”;
  4. echo “<ul>”; //starting the list
  5. echo $alert; //echo the error messages
  6. echo “</ul>”; //end the list
  7. }

Now, for the final addition, let’s send that email. We’ll want to use the “mail” function in PHP to do this because it’s simple and quick. We’ll employ the “clean_var” function to sanitize the user entered data. Here it is:

  1. ///this is earlier error code
  2. } elseif (isset($_REQUEST['message'])) {
  3. $message = “From: “ . clean_var($_REQUEST['name']) . \n;
  4. $message .= “Email: “ . clean_var($_REQUEST['email']) . \n;
  5. $message .= “Telephone: “ . clean_var($_REQUEST['tele']) . \n;
  6. $message .= “Message: \n . clean_var($_REQUEST['message']);
  7. $header = ‘From:’. clean_var($_REQUEST['email']);
  8. mail($sendto, $subject, $message, $header);
  9. echo “<script>$(\”.message\”).hide(\”slow\”).show(\”slow\”).animate({opacity: 1.0}, 4000).hide(\”slow\”); $(‘:input’).clearForm() </script>”;
  10. echo $thanks;
  11. die();
  12. }

That should just about wrap it up besides for the variables we should set at the beginning of the code. Here they are in all their glory:

  1. //        Who you want to recieve the emails from the form. (Hint: generally you.)
  2. $sendto = ‘youremail@example.com’;
  3. //        The subject you’ll see in your inbox
  4. $subject = ‘Contact from contact form’;
  5. // Message if there isn’t a mail function
  6. $mailerror = “Oops! It seems that the server can’t mail this! Try emailing us at “ . $sendto . ” instead.”;
  7. //        Message for the user when he/she fills in the form correctly.
  8. $thanks = “Thanks for the email! We’ll get back to you as soon as possible!”;
  9. //        Message for the bot when it fills in in at all.
  10. $honeypot = “You filled in the honeypot! If you’re human, try again!”;
  11. //        Various messages displayed when the fields are empty.
  12. $emptyname = ‘Entering your name?’;
  13. $emptyemail = ‘Entering your email address?’;
  14. $emptytele = ‘Entering your telephone number?’;
  15. $emptymessage = ‘Entering a message?’;
  16. //       Various messages displayed when the fields are incorrectly formatted.
  17. $alertname = ‘Entering your name using only the standard alphabet?’;
  18. $alertemail = ‘Entering your email in this format: <i>name@example.com</i>?’;
  19. $alerttele = ‘Entering your telephone number in this format: <i>555-555-5555</i>?’;
  20. $alertmessage = “Making sure you aren’t using any parenthesis or other escaping characters in the message? Most URLS are fine though!”;
  21. $alert = ; // Got to call it first in order to append the error messages
  22. $pass = 0; // Default is pass through, errors will flip

Phew! Now that was a lot of code! If this is too much to deal with right, just download the zipped file and get all of the code, html and CSS together.

If you catch any error or bloopers, please let me know! I stuck this together really quickly and I am bound to make mistakes.

original text here