Make Your Own Ajax Contact Form

pencil

Ajax is an awesome technique, which allows for server-side stuff to be done without the user having to even refresh a page.

One common use for Ajax is contact forms. So today, we're going to create just that. Once you understand how to make a contact form, you can easily figure out how to use the same techniques to do just about anything.

Because plain Ajax can be difficult for beginners, we're going to use the Ajax features included in jQuery. That's because this isn't an Ajax tutorial, just one implementation of this awesome technique.

I originally meant to make a screencast out of this, but the recording didn't go well. So, I simply made a text-based tutorial out of it.

The HTML

Of course, we have to start with the boring part. Fortunately, it's also the easiest part. We'll just put together a simple form, with all the fields we need. We'll call this file contact.html.

This is just your standard HTML form. If you're not interested in this, you can go ahead and skip to the next section.

<form id="contact" action="mail.php" method="get">
 
    <p>
        <input id="name" type="text" name="name" />
        <label for="name">Your Name</label>
    </p>
 
    <p>
        <input id="email" type="text" name="email" />
        <label for="email">Email</label>
    </p>
 
    <p>
        <input id="subject" type="text" name="subject" />
        <label for="subject">Subject</label>
    </p>
 
    <p>
        <textarea id="msg" rows="5" cols="30"></textarea>
    </p>
 
    <p>
        <input type="submit" value="Submit" />
    </p>
 
</form>

So this is just your basic HTML form, with fields for the user's name, email address, subject and message.

The PHP

Now, we're at the interesting part! Our PHP file will contain the stuff that makes everything actually work.

Let's call this file mail.php.

<?php
 
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$msg = $_GET['msg'];
 
$headers = 'From: ' . $name . ' <' . $email . '>' . "\r\n" .
	'Reply-to: ' . $email . "\r\n";
 
mail('test@example.com', $subject, $msg, $headers);
 
?>

That's really all there is to it. One line actually sends the message, the rest is just variables to make everything cleaner.

At the top, we're creating variables for the user's name, email address, subject and message. The script is getting these values from GET parameters, which we will be using later.

Next we create the headers. We just set the values for From (their name and email address) and Reply-to (their email address). We just concatenate the values together to make a single string. It ends up looking something like this:

From: John Smith <jsmith@example.com>
Reply-to: jsmith@example.com

Finally, we get to the line of code that actually does something. This is PHP's mail function, which — you guessed it — sends mail.

mail('test@example.com', $subject, $msg, $headers);

The first parameter that we include is the email address we would like to send the message to. Of course, be sure to replace it with your own.

Next is the subject, then the message, and finally the headers that we created.

The JavaScript

Since this is an Ajax tutorial, it couldn't possibly be complete without the part you've all been waiting for: The JavaScript! To make things easier for beginners, we will start out using jQuery to do this.

When initially putting this together, you can place the script within the head section of contact.html. But when actually using this on a live site, be sure to include it from an external file.

First, be sure to include the jQuery library. Not doing this can lead to some embarassment later when your script doesn't work. You can use your own, or simply use Google's jQuery CDN:

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

Below that, in between new script tags, insert the following code.

// Do this on page load
$(function() {
 
   $('#contact').submit(function() {
 
        // Hide the form
        $('#contact').hide(500);
 
        $.get('mail.php', {
            name: $('#name').val(),
            email: $('#email').val(),
            subject: $('#subject').val(),
            msg: $('#msg').val()
        });
 
        // Keeps the user on the page
        return false;
 
   });
 
});

First of all, we use $(function to make everything happen once the page is loaded.

Next, inside that, we use $('#contact').submit(). This pretty much means "When a form with an ID of contact is submitted, do the stuff that comes next."

To let the user know that somethign is happening, we hide the form with hide. I chose 500 for the duration because I think that it makes it look nice.

Next, we have the following bit of code.

$.get('mail.php', {
    name: $('#name').val(),
    email: $('#email').val(),
    subject: $('#subject').val(),
    msg: $('#msg').val()
});

Remember how we used GET parameters for the information in the PHP file? Well, this is where we're passing them in to mail.php.

For each parameter, we assign a value. Each value uses the val function to get the value of that field, to use it as a parameter.

Finally, we have one more line of code.

return false;

This is basically used to keep the user on the same page, to get that "Ajaxy" effect. There isn't really that much more to it, without having to get into extreme detail.

So once you have everything written, upload it to your server and test it out! If something goes wrong, leave a comment on this post, and I'll do my best to help sort it out.

Conclusion

You can download the complete source code.

Sorry, there's no demo. If you'd like to send me an email, feel free to use my official contact form.

I hope you enjoyed this basic introduction to creating an Ajax contact form. This is really one of the simplest things you can do, and more could be added. For example, here are just a few possible suggestions.

  • Add a new feature
  • Make this form secure
  • Include some sort of form validation
  • Make it look nicer
  • Or just take this and make it do something completely different.

Like always, if you have any questions or would like to share your thoughts, don't hesitate to leave a comment!

Stay Updated

Did you enjoy this post? Don't miss a single post by getting free updates!

10 Comments

  1. Maxi
    January 26, 2010

    Good article

  2. January 27, 2010

    Great article! Curious though - how would one go about adding a thank you message or whatever so that the viditor knew that it was properly sent and everything?

    I am going to implement this on my WordPress site - I just want a simple contact form - nothing fancy like is available via the plugin directory.

    Also - what would the PHP be to only allow access to that mail.php file from the contact.html? otherwise, it is very possible that contact spam would arise.

    • January 27, 2010

      Hmmm. To add a thank you message, you could add a div with the CSS set to display: none.

      And then you can use jQuery show() (or similar) to make it visible upon form completion.

      If you choose to go that way, you should also add a thank you message into mail.php, just for people who may have JavaScript disabled.

      As for disabling access to mail.php, I'll be sure to look into that, as it's an interesting question! I may even have a post up about that around Saturday.

  3. Christian
    October 14, 2011

    Is it possible to customize the style?

Trackbacks/Pingbacks