Web forms that don’t refresh the page

Published on January 11, 2011 under How-To, Web Development

jQuery Web Forms

In the past, it was necessary to refresh a web page when submitting a form, mainly because the methods of POST and GET needed to have the data inserted via HTTP or querystring.  Most never took too much issue with this except when the age of video and other streaming media came about.  Imagine how annoying it is to be halfway through that film trailer and you post a comment, only to have the video reset to the beginning so your comment is added.

Thanks to the development of AJAX, we now can rid ourselves of the idea of a page refresh for almost any reason.  You can see Google searches come instantly without your page changing, or Facebook statuses post immediately without the page refreshing.  I personally feel that this is the standard of things, and those making web forms should know this.  Now I'll show you how I did it.

There are many scripts out there one can easily take for free.  Mine is one of them as well, but I did doctor it up for my needs.  You can download a zip file of all the example code here, but there's also a link at the bottom if you miss this.   I separated things into two folders.  One is an example if you want a form to just email the results to you, the other if you want to post it on a MySQL database.  Everything is in PHP and Javascript, so if you're an fan, then you'll have to figure it out on your own.

I did include the version of the jQuery library that I used at the time of this blog, but I would suggest downloading the most current release and replacing the one I included with the latest one.  Now then, let's get started.

Build your form

The first step is to build your form in HTML like you would any other form.  If you're building a dynamic form of some sort where the information is fed into the fields, that's ok as well.  There's just a few requirements.  First off, you need to have your method be set to "POST" and the name put in on the initial form tag as "form".  Here's how it should look in its simplest manner:

<form method="post" name="form">

The other big requirement is on the Submit button.  You need to set up a class on it and designate it as "submit".  This is important because the JavaScript file we will attach to this form checks to see if an object with the class "submit" is clicked.

<input type="submit" value="Submit" class="submit" />

You'll also need to attach three files to this page in the head area.  One is the jQuery library, the second is the stylesheet, and the third is either the postToDB.js file or the sendViaEmail.js file.  I think it's clear from their file names which does what.  The stylesheet is optional, but you'll need it if you want to style the result messages.  You can lift those CSS codes and place them in your main stylesheet if you like.  Just make sure the page can access it.

Place in the result messages

The result messages are the messages you'll see when you click the Submit button.  The way I have it set up is when you press Submit, the string "Processing..." appears.  If an error happens, then you get the error message.  If not, then you get the success message.

The three messages are placed on the page in spanned areas that you can style with CSS as you see fit.  You can also use division tags (div) or even paragraphs.  The key is to make sure you put in the corresponding class name on each of them, and set their display to "none" using a style tag.

<span class="error" style="display:none">Please complete all fields.</span>
<span class="success" style="display:none">Thank you for your submission.</span>
<span class="processing" style="display:none">Processing...</span>

The style tag is what makes them invisible before anything happens, and the class tag can serve both as a means for you to style these pieces of text as you see fit, but also because the attached JavaScript will fade in and fade out these items based on what happens in the processing.

I generally place them right next to the submit button, but if you're savvy with CSS you can do almost anything you like.  You could make them into divisions with the z-index set higher and make a message window of some sort fade in on top of the page.  It all comes down to your creativity and skill in CSS.

Calibrate the JavaScript

I've included the JavaScript files needed to either send you results via email or post them to a database.  On the JavaScript standpoint the files are practically the same, but I kept them separate in case you might want to use both.  I know on this site I have the database one running the comment fields on my blog, while the email one runs the send a message form on the contact page.

I did put a lot of commenting in the files to help guide you.  The big thing you want to change is the fields where you designate the data coming in.  So let's say your form is for a registration with name, address, city, state, etc.  Here's what it might look like:

var firstName = J("#firstName").val();
var lastName = J("#lastname").val();
var address1 = J("#address1").val();
var address2 = J("#address2").val();
var city = J("#city").val();
var state = J("#state").val();
var zipCode = J("#zipCode").val();
var email = J("#email").val();
var dataString = 'firstName='+ firstName + '&lastName=' + lastName + '&address1=' + address1 + '&address2=' + address2 + '&city=' + city + '&state=' + state + '&zipCode=' + zipCode + '&email=' + email;

I did this longer one on purpose so you'll understand how to do it for bigger forms when you have to add more fields.  The variable name next to the "var" designation can be anything you like, but the names in the ("#_________") must match the fields you're pulling in from the web form.  It's just good practice to keep the names fluid throughout the process, but some might not want to do that.

On line 22 of the JavaScript, you'll then see this as the beginning of an if statement:

if(field1=='' || field2=='' || field3=='') {

This if statement is only going to check to make sure fields were filled out.  So you would replace those field names with the fields you want to be mandatory.  Therefore, let's say you only want the first name, last name, zip code, and email fields as mandatory and the rest optional.  Your line will look like this:

if(firstName=='' || lastName=='' || zipCode=='' || email=='') {

This if statement looks to see if the fields in it are empty.  If so, then the script tells the error message to fade in while the success and processing messages stay hidden.  I'm sure even the savvy JavaScript developers could even make those fields be more specific, like checking for an @ symbol in the email field.

Now, if the designated fields have content in them, the JavaScript will process the form.  Everything after the else is what you need to focus on.  On line 29, you would designate the PHP page that would process the data.  Again I included two examples.  One if you're posting to a database and one for sending via email.  It just shows mainly how your processing is put on a different PHP document and called upon.  I'm sure this can also be done in ASP.

Other things to note would be that you can play with the fade speed by changing those "100" integers to lower numbers.  The document.form.reset() is there to clear the form when it's processed successfully.  I mainly like forms to work that way.  It also shows why you put a name on the opening form tag.

Now if you're wondering about the variable J or K (depending on which file you're looking at) and how they're spread all over the JavaScript file, this is to keep this file from interfering with other jQuery-driven files.  On this site, the navigation fade in/fade out is run by jQuery, as well as the Lightbox.  Setting up the jQuery.noConflict() will make sure you don't have scripts playing with one another.  I did that here simply to make life easier on you.  It simply tells the browser that anything run on this page through jQuery is only meant for this page.  Therefore if you have functions designated on other files, you won't see one calling on the other accidentally.

Set up your PHP form processing

Again, to make life easier, I made sure to put plenty of comments into these pages to show you how to fix them up for your own needs.  Feel free to delete the comments if you are using them and want your pages leaner for some odd reason.

postToDB.php is if you're going to post things on a database table.  I separated the connection variables on dbConnect.php again because it's a good practice for making a database-driven site.  One small include code at the top and you have access to your connection anywhere.

On the page itself you can see the end result is similar to how you put stuff into a database.  You pull down the data from the HTTP (sent via POST) and then create the SQL string that takes care of the rest when you run the MySQL query.

sendViaEmail.php is the scenario if you just want to email the results to an email address.  On my included script you would change the fields to match the incoming data.  After that it's just changing the "" on line 14 to whatever email address you want receiving this email, and changing out the other fields as you see fit.

I didn't get deep into how these files work because if you use PHP then you should know it.  However, I'm always open to help if you have questions on how to prepare these pages for your own usage.

That's pretty much it.  It should work provided you put the files in the right spots and changed up the right information, without errors.  Give it a shot, leave comments if you have trouble.

Download example files Download the example files from this article

Here's a link for more on that jQuery.noConflict() function and how I learned to use it:

Tags: web forms, jquery, ajax, web development, php

comments powered by Disqus