<p>There are so many different javascript frameworks out there, but I have recently started to use <a href="http://jquery.com">jQuery</a>, 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.</p>



<h2 class="replaceHeadline">Start with a Regular Form</h2>

<p>First, I am going to build a <a href="//assets.trevor-davis.com/play/jqueryajaxform/">regular form</a>. 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:</p>

<ol><li>User fills out the form.</li>
 <li>User submits the form to the server.</li>
 <li>Server side script makes sure that there are no blank fields and that the email addresses are valid.</li>
 <li>If there are errors, show the form again with the error messages.</li>
 <li>If there are no errors, send the email.</li>
</ol><p>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.</p>

<h2 class="replaceHeadline">Add in JavaScript</h2>

<p>OK, so next, I am going to make an <a href="//assets.trevor-davis.com/play/jqueryajaxform/ajaxed/">AJAX version, which is a duplicate of the first form</a>. The only other things I am going to include on the page are the jquery library (<a href="http://docs.jquery.com/Downloading_jQuery">which you can download here</a>) and my JavaScript to process this form.</p>


<h3 class="replaceHeadline">Firing My Script When the Document is Ready</h3>
<p>jQuery has a nice little function to have you script start when the document is ready:</p>

<div class="codeblock"><code>
$(document).ready(function(){<br /> //Script goes here<br />}); 

</code></div>

<p>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 <strong>submit</strong> to my button, so it makes it really easy to reference:</p>

<div class="codeblock"><code>
$(document).ready(function(){<br /> $("#submit").click(function(){<br />  return false;<br /> });<br />}); 

</code></div>

<p>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:</p>

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

</code></div>


<h3 class="replaceHeadline">Error Checking</h3>

<p>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:</p>

<div class="codeblock"><code>
$(document).ready(function(){<br /> $("#submit").click(function(){<br />  $(".error").hide();<br />  var hasError = false;<br />  var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;<br /><br />  var emailToVal = $("#emailTo").val();<br />  if(emailToVal == '') {<br />   $("#emailTo").after('&lt;span class="error"&gt;You forgot to enter the email address to send to&lt;/span&gt;');<br />   hasError = true;<br />  } else if(!emailReg.test(emailToVal)) {<br />   $("#emailTo").after('&lt;span class="error"&gt;Enter a valid email address to send to.&lt;/span&gt;');<br />   hasError = true;<br />  }<br /><br />  return false;<br /> });<br />}); 

</code></div>

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

<ul><li>Get the value of the email to address input.</li>
 <li>If it is empty, add an error message after the input</li>
 <li>If it has an invalid email address, add an error message after the input.</li>
</ul><p>Now, we just need to repeat the error checking for the other form fields:</p>

<div class="codeblock"><code>
$(document).ready(function(){<br /> $("#submit").click(function(){<br />  $(".error").hide();<br />  var hasError = false;<br />  var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;<br /><br />  var emailToVal = $("#emailTo").val();<br />  if(emailToVal == '') {<br />   $("#emailTo").after('&lt;span class="error"&gt;You forgot to enter the email address to send to.&lt;/span&gt;');<br />   hasError = true;<br />  } else if(!emailReg.test(emailToVal)) {<br />   $("#emailTo").after('&lt;span class="error"&gt;Enter a valid email address to send to.&lt;/span&gt;');<br />   hasError = true;<br />  }<br /><br />  var emailFromVal = $("#emailFrom").val();<br />  if(emailFromVal == '') {<br />   $("#emailFrom").after('&lt;span class="error"&gt;You forgot to enter the email address to send from.&lt;/span&gt;');<br />   hasError = true;<br />  } else if(!emailReg.test(emailFromVal)) {<br />   $("#emailFrom").after('&lt;span class="error"&gt;Enter a valid email address to send from.&lt;/span&gt;');<br />   hasError = true;<br />  }<br /><br />  var subjectVal = $("#subject").val();<br />  if(subjectVal == '') {<br />   $("#subject").after('&lt;span class="error"&gt;You forgot to enter the subject.&lt;/span&gt;');<br />   hasError = true;<br />  }<br /><br />  var messageVal = $("#message").val();<br />  if(messageVal == '') {<br />   $("#message").after('&lt;span class="error"&gt;You forgot to enter the message.&lt;/span&gt;');<br />   hasError = true;<br />  }<br /><br />  return false;<br /> });<br />}); 

</code></div>

<p>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 <a href="//assets.trevor-davis.com/uploads/images/content/2008/01/submitform.js">see the whole script</a>.</p>

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

<div class="codeblock"><code>
if(hasError == false) {<br /> $(this).hide();<br /> $("#sendEmail li.buttons").append('&lt;img src="/images/template/loading.gif" alt="Loading" id="loading" /&gt;');<br />} 

</code></div>

<h3 class="replaceHeadline">Submit the POST Request</h3>
<p>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:</p>

<div class="codeblock"><code>
$.post("/play/jqueryajaxform/sendEmail.php",<br />   { emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },<br />    function(data){<br />  $("#sendEmail").slideUp("normal", function() {<br /><br />   $("#sendEmail").before('&lt;h1&gt;Success&lt;/h1&gt;&lt;p&gt;Your email was sent.&lt;/p&gt;');<br />  });<br /> }<br />); 

</code></div>

<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 <a href="http://docs.jquery.com/Main_Page">jQuery Documentation</a>. So go ahead, send yourself some emails to see for yourself.</p>

<h3 class="replaceHeadline">Update…</h3>
<p>I was asked in the comments if I could include the PHP script. So as requested, here are the files that are used:</p>
<ul><li><a href="//assets.trevor-davis.com/uploads/images/content/2008/01/index.phps">index.php</a></li>
<li><a href="//assets.trevor-davis.com/uploads/images/content/2008/01/verify.phps">verify.php</a></li>
<li><a href="//assets.trevor-davis.com/uploads/images/content/2008/01/sendemail.phps">sendEmail.php</a></li>
<li><a href="//assets.trevor-davis.com/uploads/images/content/2008/01/thanks.phps">thanks.php</a></li>
</ul>