#AJAX, #JavaScript, #jQuery, #php, #Web Design

jQuery AJAX Form Submission

I’ve never been much of a programmer; and I’m probably unusually intimidated by JavaScript. I can’t explain its effect on me, considering what I’ve tackled with php (which, I suppose is arguably pretty simple and inefficient stuff), but it’s not something I’m proud of.

At any rate, this week I decided to tackle a bit of a problem that has been bothering me for as long as I’ve had the current design on my portfolio site.
The portfolio side of things exists as a single page site with work samples, a little information, and a contact form. The contact form would require that you reload the page upon submission in order to process and send the message, which always seemed like a jarring experience from a user interaction perspective.
In order to solve that problem, my solution was the ever popular: AJAX.

I’ve used some jQuery plugins in the past, so I was familiar with the framework; after doing some reading and thinking about compatibility with my current setup, I decided that jQuery’s built in AJAX implementation, and animation effects, would be just about perfect for my needs. Why? Because the jQuery framework is incredibly useful to me, as a designer, with little time for figuring out how to implement all of these fancy user interactions with JavaScript. Plus, it’s the framework I use for everything.

Let’s Get Programming

Where does my implementation begin? Well it begins by adding the jQuery files to the head of your page:

<script type="text/javascript" src="path/to/jquery.js"></script>

Then we’ll setup the function that will help us load up what we need. This is the function we will place all of our jQuery code in:

$(document).ready(function(){
   //some code
});

jQuery is nice for many reasons, one being the way in which events are initiated. [Karl Swedberg](http://www.learningjquery.com/2006/09/introducing-document-ready) says:

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don’t have to put any “behavioral” markup in the HTML. You can separate all of your javascript/jQuery into a separate file where it’s easier to maintain and where it can stay out of the way of the content.

That’s useful for content/style/function separation, and is really, really handy. And perhaps one of the reasons I avoided JavaScript for so long was because it lacked something this simple to begin with.

Let’s start the AJAX

So first we need to setup what it is we’re going to be evaluating, which is basically the submit event of form #contactform. When we click submit, our function will run.

$("form#contactform").submit(function() {
   //some code
});

This function will have to do a number of things for us. First it needs to store our input values into variables in order to process them and POST them later. Then we’ll take those input variables and place them all in a variable (formData) formatted for ease of use for the POST process.

var name     = $('#name').attr('value');
var formData = "name="+ name + "&email=" + -->
email + "&message=" + message + "&color=" + color;

Following this bit of code it’s time to use jQuery.ajax in order to submit our form information asynchronously.

$.ajax({
   type: "POST",
   url: "send.php",
   data: formData,
   success: function(del){
      //success code placed here
   }
});

The options for jQuery.ajax in my code here are: type, the method that will be used when sending the form data, in this case POST; url, or the location where we will be sending our form data; data, the data to be sent; and success, what will we do when it has completed successfully. Check out jQuery.ajax for more information on options.

That’s pretty much it. I’ve setup the PHP file to deal with the posted data, and there are many ways to do this, so use your favorite and do it in the way you normally would.

My Code

Ok, so in my code, I’ve done a bit of rudimentary form field validation and bot protection. Additionally, I’ve added a little bit of effect animation and utilized the DOM to display confirmation or error messages, a loading graphic, and to fade out certain elements of the form. I discovered a bit of a problem when my inbox was full of spam messages from this form. In my PHP file, I’ve had to add a little bit of validation there as well, in case a user, or a bot, is attempting to the use the form without JavaScript enabled.

The JavaScript:

$(document).ready(function(){
$("form#contactform").submit(function() {
    var name     = $('#name').attr('value');
    var email    = $('#email').attr('value');
    var message  = $('#message').attr('value');
    var color    = $('#color').attr('value');
    var formData = "name="+ name + "&email=" + email + "&message=" + message + "&color=" + color;
    $('#contact_form > div#error').hide("fast");
    $('#contact_form > div#success').hide("fast");
    $('#contact_form > div#problem').hide("fast");
    //Test whether fields have been filled and rudimentary bot test has passed then send via jquery.ajax
    if (name != null && email != null && message != null) {
        if (color == "blue" || color == "Blue"){
            $("#contactform").before('<div id="loading" style="text-align:center;"><img src="images/loadingForm.gif" /></div>').slideDown("fast");
            $("#submitButton").hide();
            $("#contactform").fadeTo("fast", 0.33);
            $.ajax({
                 type: "POST",
                 url: "send.php",
                data: formData,
                success: function(del, text){
                      $("form#contactform").before('<div class="error" id="success">Thank you for your message!</div>').slideDown("slow");
                      $('#name').attr('value', '')
                      $('#email').attr('value', '')
                      $('#message').attr('value', '')
                      $('#color').attr('value', '')
                      $('#contact_form > div#loading').slideUp("slow");
                      $("#submitButton").show();
                      $("#contactform").fadeTo("slow", 1);
                }
            });
        }else{
            $("#contactform").before('<div class="error" id="error">You must fill in the color of the sky!</div>').slideDown("slow");
            $('#contact_form > div#loading').slideUp("fast");
            $("#submitButton").show();
            $("#contactform").fadeTo("fast", 1);
        }
    } else {
        $("#contactform").before('<div class="error" id="problem">You must fill in all of the fields!</div>').slideDown("slow");
        $('#contact_form > div#loading').slideUp("fast");
        $("#submitButton").show();
        $("#contactform").fadeTo("fast", 1);
    }
        return false;
    });
});

The form:

<form name="contact_form" id="contactform" method="post" action="send.php">
<div class="column span-4 first last">
<label for="name">Full Name:</label>
<input type="text" id="name" class="textfield" name="name" value="" />
</div>
<div class="column span-4 first last">
<label for="email">Email: </label>
<input type="text" id="email" class="textfield" name="email" value="" />
</div>
<div class="column span-4 first last">
<label for="color">What color is the sky? </label>
<input type="text" id="color" class="textfield" name="color" value="" />
</div>
<div class="column span-4 first last">
<label for="message">Message:</label>
<textarea class="textfield" id="message" name="message" cols="10" rows="8"></textarea>
</div>
<div class="clear"></div>
<div class="text-right" id="submitButton">
<input type="image" name="send" value="Send" src="images/submit.gif"/>
</div>
</form>

Conclusion

That’s all I’ve done. I’m no programmer, and I apologize for not knowing how to best explain what I’ve done, but hopefully getting a chance to look at some code will help you figure it out. If you have questions, I would be glad to help as much as I can.

Special thanks to Ryan Coughlin for helping me through this by offering up his code, which is what I based my AJAX form on.