Download | Demo
Step 1 - Build the HTML Form
Let’s take a look at our html markup. We begin with our basic html form- <div id="contact_form">
- <form name="contact" action="">
- <fieldset>
- <label for="name" id="name_label">Name</label>
- <input type="text" name="name" id="name" size="30" value="" class="text-input" />
- <label class="error" for="name" id="name_error">This field is required.</label>
- <label for="email" id="email_label">Return Email</label>
- <input type="text" name="email" id="email" size="30" value="" class="text-input" />
- <label class="error" for="email" id="email_error">This field is required.</label>
- <label for="phone" id="phone_label">Return Phone</label>
- <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
- <label class="error" for="phone" id="phone_error">This field is required.</label>
- <br />
- <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
- </fieldset>
- </form>
- </div>
Be sure to not miss that div in your own form as we will be needing this wrapper div later on. You
might also notice that I have left both the action and the method parts of the form tag blank. We
actually don’t need either of these here, because jQuery takes care of it all later on.
Another important thing to be sure to include is the id values for each input field. The id values
are what your jQuery script will be looking for to process the form with.
I’ve added some css styles and a background image in Photoshop to produce the following form:
Step 2 - Begin Adding jQuery
The next step in the process is to add some jQuery code. I’m going to assume that you have downloaded jQuery, uploaded to your server, and are referencing it in your webpage.Next, open up another new javascript file, reference it in your html as you would any normal javascript file,
and add the following:
- $(function() {
- $(".button").click(function() {
- // validate and process form here
- });
- });
Step 3 - Write Some Form Validation
- $(function() {
- $('.error').hide();
- $(".button").click(function() {
- // validate and process form here
- $('.error').hide();
- var name = $("input#name").val();
- if (name == "") {
- $("label#name_error").show();
- $("input#name").focus();
- return false;
- }
- var email = $("input#email").val();
- if (email == "") {
- $("label#email_error").show();
- $("input#email").focus();
- return false;
- }
- var phone = $("input#phone").val();
- if (phone == "") {
- $("label#phone_error").show();
- $("input#phone").focus();
- return false;
- }
- });
- });
the page first loads, but also when you click submit, in case one of the messages was shown to the user previously. Each error message should only appear if validation doesn’t work out.
We validate by first checking if the name field was left blank by the user, and if it is, we then show the label with id of name_error. We then place the focus on the name input field, in case the user
is at all confused about what to do next! (I have learned to never assume too much when it comes to form users).
To explain in more detail how we are making this happen, we set a variable ‘name’ to the value of the input field with id “name” — all with one line of jQuery:
- var name = $("input#name").val();
id “name_error”:
- if (name == "") {
- $("label#name_error").show();
- }
- if (name == "") {
- $("label#name_error").show();
- $("input#name").focus();
- return false;
- }
the purpose of this tutorial)! What return false does is it prevents the user from proceeding any further
without filling out the required field(s).
Step 4 - Process our Form Submission with jQuery’s AJAX Function
Now we get to the heart of the tutorial — submitting our form without page refresh, which sends the form values to a php a script in the background. Let’s take a look at all the code first, then I will break down into more detail next. Add the following code just below the validation snippet we added previously (and before the button click function is closed out):- var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
- //alert (dataString);return false;
- $.ajax({
- type: "POST",
- url: "bin/process.php",
- data: dataString,
- success: function() {
- $('#contact_form').html("<div id='message'></div>");
- $('#message').html("<h2>Contact Form Submitted!</h2>")
- .append("<p>We will be in touch soon.</p>")
- .hide()
- .fadeIn(1500, function() {
- $('#message').append("<img id='checkmark' src='images/check.png' />");
- });
- }
- });
- return false;
Recall previously, we had set a variable ‘name’ with the value of the input field with id “name”, like so:
- var name = $("input#name").val();
- var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
close attention!
- $.ajax({
- type: "POST",
- url: "bin/process.php",
- data: dataString,
- success: function() {
- //display message back to user here
- }
- });
- return false;
There are more advanced things you can do here, other than sending an email and giving a success message. For example you could send your values to a database, process them, then display the results back to the user. So if you posted a poll to users, you could process their vote, then return the voting results, all without any page refresh required.
Let’s summarize what happened in our example, to be sure we have covered everything. We grabbed our form values with jQuery, and then placed those into a string like this:
- var name = $("input#name").val();
- var email = $("input#email").val();
- var phone = $("input#phone").val();
- var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
process finishes successfully, we display a message back to the user and add return false so that our page does not refresh:
- $.ajax({
- type: "POST",
- url: "bin/process.php",
- data: dataString,
- success: function() {
- $('#contact_form').html("<div id='message'></div>");
- $('#message').html("<h2>Contact Form Submitted!</h2>")
- .append("<p>We will be in touch soon.</p>")
- .hide()
- .fadeIn(1500, function() {
- $('#message').append("<img id='checkmark' src='images/check.png' />");
- });
- }
- });
- return false;
Step 5 - Display a Message Back to the User
Let’s briefly look at the part of the code that displays our message back to the user, to finish out the tutorial.First, we change the entire contents of the contact_form div (remember I said we would be needing that div) with the following line:
- $('#contact_form').html("<div id='message'></div>");
- $('#message').html("<h2>Contact Form Submitted!</h2>")
- .append("<p>We will be in touch soon.</p>")
- .hide()
- .fadeIn(1500, function() {
- $('#message').append("<img id='checkmark' src='images/check.png' />");
- });
So if you have a contact form on your website, a login form, or even more advanced forms that process values through a database and retrieve results back, you can do it all easily and efficiently, and perhaps most importantly, you enhance the end user experience with your website by providing interactivity without their having to wait for the page to reload.
Conclusion
I would like to add some final words about the demo example provided. In the demo, you may notice that there is in fact one plugin being used – the runonload.js file. I did state at the beginning of the tutorial that we would not be using any plugins, and then you find in the demo there is an extra runonload script, so some explanation may be necessary! For anyone interested in seeing a live working demo, you can view my website’s SEO consulting form.The only use I made with runonload actually has nothing to do with processing the form. So you can accomplish the ajax functions completely without any extra plugins. I only used runonload to focus the name input field on page load. It has been my experience that calling runonload can sometimes be a better replacement for jQuery’s native document ready function, and I found that to be the case while putting together this tutorial. For some reason the focus() function would not work on page load using jQuery’s native document ready function — but it did work with runonload, and that is why you find it as part of the example. So if you know of a way to accomplish that without using runonload I would be happy to hear from you about that.
No comments:
Post a Comment