Slick (and Easy) Ajax Contact Form With jQuery

jQuery is basically amazing. It's no-brainer syntax makes it incredibly easy to learn, and it's chaining cuts tons of would-be Javascript into one or two lines. As an example of this, let me show how you stupidly easy it is to make a really slick, totally useful Ajax contact form using jQuery.

Here's the demo. Another (more heavily styled) example of this be seen on the Capsize Designs "About" page.

Our goal:

- A plain old form contaning:
1. Text input for name
2. Text input for email
3. Textarea for message
4. Submit Button

- When submitted, the form's fields will be sent (via AJAX) to a separate page ('send.php')
- The page will attempt to send the email, and return a code back to the sending page
- If successful, a success message will fade in, and the form will reset. The page will NOT reload.
- If unsuccessful, an error message will fade in.

So let's get started. The HTML is pretty simple. We have a basic form, blah blah. The only curveball is that we're going to be adding three paragraphs before the form, one for each status message that could be output, and set them to display: none;. This way, we can selectively fade in the appropriate message after the form is submitted. Here's the code:

HTML:
  1. <p id='success' style="display:none;">Your email is sent! Thanks!</p>
  2. <p id='bademail' style="display:none;">Please enter a valid email.</p>
  3. <p id='badserver' style="display:none;">Your email failed. Try again later.</p>
  4. <form id="myForm" action="send.php" method="post">
  5.     <p><label for="nameinput">Name:</label></p>
  6.     <input type="text" id="nameinput" name="name" size='27'/> <br /><br />
  7.     <p><label for="emailinput">Email:</label></p>
  8.     <input type="text" id="emailinput" name="email" size='27'/> <br /><br />
  9.     <p><label for="commentinput">Comments:</label></p>
  10.     <textarea name="comment" id="commentinput" cols='25' rows='4'></textarea> <br /><br />
  11.     <center><input type="submit" id="submitinput" value="Send it!" /> </center>
  12. </form>

As you can see, the form submits itself to 'send.php' via the POST method. The next thing we have to do is create this 'send.php' page which will take the inputs, check them for validity, and then send them in an email to an address in the file.

PHP:
  1. <?php
  2.     error_reporting(E_NOTICE);
  3.  
  4.     function valid_email($str)
  5.     {
  6.         return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
  7.     }
  8.  
  9.     if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
  10.     {
  11.         $to = "EMAIL@EMAILADDRESS.COM";
  12.         $headers =  'From: '.$_POST['email'].''. "\r\n" .
  13.                 'Reply-To: '.$_POST['email'].'' . "\r\n" .
  14.                 'X-Mailer: PHP/' . phpversion();
  15.         $subject = "Contact Form";
  16.         $message = htmlspecialchars($_POST['comment']);
  17.        
  18.         if(mail($to, $subject, $message, $headers))
  19.         {
  20.             echo 1; //SUCCESS
  21.         }
  22.         else {
  23.             echo 2; //FAILURE - server failure
  24.         }
  25.     }
  26.     else {
  27.         echo 3; //FAILURE - not valid email
  28.     }
  29. ?>

This is probably the heaviest part of the process, but luckily you can pretty much use this code as-is and just replace EMAIL@EMAILADDRESS.COM with your email. The only real important parts are the echo statements at the end. These return the status codes to tell us if the email was successfully sent, and if not, why not? In this case, a '1' means success, a '2' means server failure (HINT: You CANNOT run this on localhost, and doing so will give you this error) and '3' means invalid email address or no characters were entered in the comment box.

As it is, the code will work. The email should send. But we web designers are greedy folk, and we want something more. Let's throw in a little AJAX goodness with the help of our good friend jQuery. The jQuery Form Plugin is a little lifesaver that turns a regular form into an AJAX form with one line. We can then pass our 'send.php' page's status code back to this function as a parameter, and decide which error message to display based on that code. Here's the Javascript for all of this:

JavaScript:
  1. <script type="text/javascript" src="jquery-1.2.3.min.js"></script>
  2. <script type="text/javascript" src="jquery.form.js"></script>
  3. <script type="text/javascript">
  4.     $(document).ready(function(){
  5.         $('#myForm').ajaxForm(function(data) {
  6.             if (data==1){
  7.                 $('#success').fadeIn("slow");
  8.                 $('#myForm').resetForm();
  9.             }
  10.             else if (data==2){
  11.                 $('#badserver').fadeIn("slow");
  12.             }
  13.             else if (data==3)
  14.             {
  15.                 $('#bademail').fadeIn("slow");
  16.             }
  17.         });
  18.     });
  19. </script>

If you aren't familiar with jQuery syntax, feel free to learn a little bit or just ignore it altogether. Basically, the $(document).ready(function(){ tells the page to execute all this stuff as soon as it's ready for it. The ajaxForm() function tells the page to stay right where it is when the form is submitted. All the rest of that simply fades in the appropriate error message.

And that's pretty much it. Told you it was easy. If you have any questions, feel free to add them as a comment. If you're lazy like me, you can just download the files here.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Fark
  • Furl
  • YahooMyWeb

17 Responses to “Slick (and Easy) Ajax Contact Form With jQuery”

  1. Nick Says:

    Hey great tutorial, little question I can’t seem to get the js working for my site.

    http://www.nickd.co.nz

    Any ideas?

    Thanks

  2. admin Says:

    Sure thing, Nick. I have emailed you about it.

  3. SEO Boot Camp Says:

    I enjoyed your writing style and I’ve added you to my Reader. Keep these posts coming.

  4. PierreYves Says:

    Hello,

    Do you know how i could make this form still usable if the user has disabled JS (having a “message sent” instead of the “1″ would actually be enough!)

    Thanks in advance!

  5. Alister Cameron // Blogologist Says:

    Hi there. Thanks for this. Simple and effective… however, incomplete. I’ve updated the PHP to something more like this:

    <?php
        error_reporting(E_NOTICE);
        function valid_email($str)
        {
            return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
        }
        if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
        {
            $to = "EMAIL@DOMAIN.COM";
            $headers =  'From: '.$_POST['email'].''. "\r\n" .
                    'Reply-To: '.$_POST['email'].'' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();
            $subject = "A new website form submission...";
           
            $message = "You have received a message via your website:\r\n\r\n";
            $message .= "==================================================\r\n";
            $message .= "Name: " . htmlspecialchars($_POST['name']) . "\r\n";
            $message .= "Email: " . $_POST['email'] . "\r\n";
            $message .= "Phone: " . $_POST['phone'] . "\r\n";
            $message .= "Option: " . $_POST['option'] . "\r\n";
            $message .= "Comment:\r\n\r\n" . htmlspecialchars($_POST['comment']) . "\r\n";
            $message .= "==================================================\r\n\r\n";
            $message .= "If you hit 'reply', you will reply to the author.\r\n\r\n";
           
            if(mail($to, $subject, $message, $headers, '-fEMAIL@DOMAIN.COM'))
            {
                echo 1; //SUCCESS
            }
            else {
                echo 2; //FAILURE - server failure
            }
        }
        else {
            echo 3; //FAILURE - not valid email
        }
    ?>

    I also updated the jQuery to handle things a bit more correctly… if you first messed up the email address, and then submitted the form correctly, it didn’t delete the earlier error message. I’ve also made it so that if a form is properly submitted the form itself then fades out:

        jQuery(document).ready(function($){
            $('#myForm').ajaxForm(function(data) {
                if (data==1){
                    $('#success').fadeIn("slow");
                    $('#bademail').fadeOut("slow");
                    $('#myForm').resetForm();
                    $('#myForm').fadeOut("slow");
                }
                else if (data==2) $('#badserver').fadeIn("slow");
                else if (data==3) {
                    $('#bademail').fadeIn("slow");
                    $('#emaillabel').css("color","red");
                    $('#emailinput').focus();
                }
            });
        });

    Hope that’s helpful to some!

    Cheers,

    -Alister


    Alister Cameron // Blogologist
    http://www.alistercameron.com

    Mob. 04 0404 5555
    Fax 03 8610 0050

    Skype: alistercameron
    Yahoo: Alister_Cameron
    Twitter: alicam

  6. sarah coffey Says:

    I love this script but I can’t seem to get mine working. Is there anything obvious I’m overlooking?? http://www.macksgrill.net/contact
    I haven’t styled it or positioned it yet, just want to get it functioning. Any help would greatly appreciated. Thanks!

  7. Mike Says:

    @sarah

    I can’t even get the contact form to open to test it. Any thoughts?

    P.S. Nice job theming drupal (a.k.a. taming the beast). It looks great.

  8. MaverickKK Says:

    Yahooooo

  9. Blog Me I’m famous » 16 exemples et sources de formulaires Ajax Says:

    […] Easy Ajax Contact Form (jQuery) - Demo […]

  10. Andy Says:

    thanks for the script and the corrections! it will be really usefull. :)

  11. 16+ Ücretsiz Ajax İletişim Formu | Batuhan Bulak Says:

    […] Easy Ajax Contact Form (jQuery)| Demo […]

  12. çiçek siparişi Says:

    very thanks

  13. Reseller Hosting Says:

    Great info.Very good article.Bookmarked your blog plz keep it up :)

  14. Ty Says:

    Love the contact form and will be using it on my website.

  15. Matt Berridge Says:

    Have been trawling tutorials and scripts for hours and this one just takes the biscuit!

    Amazingly simple. Thank you so much :)

  16. The Making Of… (Resources) - Blog - Inspire Says:

    […] Capsize Designs Ajax Contact Form - Combined with the jQuery form plugin, an amazingly simple Ajax method of sending contact form details without a page refresh. Every other method I tried for the websites contact form was so much more complicated or lacked accessibility […]

  17. devesto » Blog Archive » Miracles of jQuery Says:

    […] jQuery Contact form - an extremely simple jQury+AJAX powered contact form provided by Capsize designs. […]

Leave a Reply