Sep 08, 2007

Ajax Forms with jQuery

There are so many different javascript frameworks out there, but I have recently started to use jQuery, and I love it. Not only is the library much smaller than others, but it is so simple to use. I wanted to show how easy it is to turn a regular form into a AJAX form.

Start with a Regular Form

First, I am going to build a regular form. The form is just going to be a basic email form. You enter an email address to send to, an email address to send from, a subject, and a message. All fields are required. So the process of the form is:

  1. User fills out the form.
  2. User submits the form to the server.
  3. Server side script makes sure that there are no blank fields and that the email addresses are valid.
  4. If there are errors, show the form again with the error messages.
  5. If there are no errors, send the email.

Ok, so this form is pretty simple, and doesn’t take much time to submit since it’s so short, but let’s see how much better we can make it with a little jQuery.

Add in JavaScript

OK, so next, I am going to make an AJAX version, which is a duplicate of the first form. The only other things I am going to include on the page are the jquery library (which you can download here) and my JavaScript to process this form.

Firing My Script When the Document is Ready

jQuery has a nice little function to have you script start when the document is ready:

$(document).ready(function(){
 //Script goes here
}); 

OK, easy enough. Now, let’s make something happen when the button to submit the form is clicked. I was smart enough to add an id of submit to my button, so it makes it really easy to reference:

$(document).ready(function(){
 $("#submit").click(function(){
  return false;
 });
}); 

First things first, I’m going to hide anything with the class of error if it’s showing (which nothing will be unless the form is unsuccessfully submitted twice). I also create a variable that I am going to use later to see if the form has an error and a variable to store the email regular expression:

$(document).ready(function(){
 $("#submit").click(function(){
  $(".error").hide();
  var hasError = false;
  var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  return false;
 });
}); 

Error Checking

Now that we’ve got the beginning of the script setup, we need to do the error checking. So first, let’s check to make sure that the email to address is not empty or invalid:

$(document).ready(function(){
 $("#submit").click(function(){
  $(".error").hide();
  var hasError = false;
  var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  var emailToVal = $("#emailTo").val();
  if(emailToVal == '') {
   $("#emailTo").after('<span class="error">You forgot to enter the email address to send to</span>');
   hasError = true;
  } else if(!emailReg.test(emailToVal)) {
   $("#emailTo").after('<span class="error">Enter a valid email address to send to.</span>');
   hasError = true;
  }

  return false;
 });
}); 

Remember, the email address to send to input has an id of emailTo. What that code is saying is:

Now, we just need to repeat the error checking for the other form fields:

$(document).ready(function(){
 $("#submit").click(function(){
  $(".error").hide();
  var hasError = false;
  var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  var emailToVal = $("#emailTo").val();
  if(emailToVal == '') {
   $("#emailTo").after('<span class="error">You forgot to enter the email address to send to.</span>');
   hasError = true;
  } else if(!emailReg.test(emailToVal)) {
   $("#emailTo").after('<span class="error">Enter a valid email address to send to.</span>');
   hasError = true;
  }

  var emailFromVal = $("#emailFrom").val();
  if(emailFromVal == '') {
   $("#emailFrom").after('<span class="error">You forgot to enter the email address to send from.</span>');
   hasError = true;
  } else if(!emailReg.test(emailFromVal)) {
   $("#emailFrom").after('<span class="error">Enter a valid email address to send from.</span>');
   hasError = true;
  }

  var subjectVal = $("#subject").val();
  if(subjectVal == '') {
   $("#subject").after('<span class="error">You forgot to enter the subject.</span>');
   hasError = true;
  }

  var messageVal = $("#message").val();
  if(messageVal == '') {
   $("#message").after('<span class="error">You forgot to enter the message.</span>');
   hasError = true;
  }

  return false;
 });
}); 

Ok, error checking is done. If there are no errors, we need to send the email via an AJAX request. I’m not going to include the whole script here, just because it’s getting long, but you can see the whole script.

So, there are no errors. Let’s remove the button from the form, and add in a loading graphic:

if(hasError == false) {
 $(this).hide();
 $("#sendEmail li.buttons").append('<img src="/images/template/loading.gif" alt="Loading" id="loading" />');

Submit the POST Request

Ok, now let’s send the values via an AJAX POST request to our send email script that just sends the email. Once the request is completed, let’s hide the form and display a success message:

$.post("/play/jqueryajaxform/sendEmail.php",
   { emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },
    function(data){
  $("#sendEmail").slideUp("normal", function() {

   $("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');
  });
 }
); 

Pretty nice huh? So now, you have a perfectly accessible form. It works fine without JavaScript. But it works even better with JavaScript. I highly recommend checking out the jQuery Documentation. So go ahead, send yourself some emails to see for yourself.

Update…

I was asked in the comments if I could include the PHP script. So as requested, here are the files that are used:

Categories