07 April 2010

Ajax Forms

Categories:  Web  jQuery  Ajax

How to simply change static old type HTML forms into Ajax handled forms.

Ajax is todays standard for handling data manipulation on Internet sites. It lets you make your site behave in more dynamic and asynchronous way. Typically used Ajax function are the ability to inform the user that his data is being handled, and reloading not whole page but only the parts of it's content, that actually should be reloaded.

Recently I needed to add contact email forms to my site. As I'm using Content Management System, I was forced to use the plug-in for building forms which comes with the tool I use. Unfortunately this plug-in is total not Ajax ready. This way created forms are acting the old way. The user clicking Send will not be notified about the data manipulation, which may end up in clicking many times and sending information multiple times to my server. This is not the way I would like my page to act. So I decided I need to change this. I spend some time looking for information in Internet and I found quite simple solution to my problem which I will try to share here.

There is a nice API based on jQuery called Form Plug-in. Using it you can change your old HTML forms into Ajax handled dynamic forms. All you need to do is to make sure that you create the script which will operate on uniquely identified forms.

Let start with showing you how the normal static forms are looking like on my site:

View the HTML form
  1. <div id="email_form">
  2. <!-- Start FormBuilder Module (0.6.1) -->
  3. <form enctype="multipart/form-data" action="http://www.kardasa.pl/english/email_form_eng.html" method="post" id="m6c9f9moduleform_1">
  4. <div class="hidden">
  5. <input type="hidden" value="FormBuilder,m6c9f9,default,1" name="mact">
  6. <input type="hidden" value="70" name="m6c9f9returnid">
  7. <input type="hidden" value="70" name="page">
  8. <input type="hidden" value="1" name="m6c9f9fbrp_callcount">
  9. </div>
  10. <div>
  11. <input type="hidden" value="13" name="m6c9f9form_id">
  12. <input type="hidden" value="en_US" name="m6c9f9lang">
  13. <input type="hidden" value="2" name="m6c9f9fbrp_continue">
  14. <input type="hidden" value="1" name="m6c9f9fbrp_done">
  15. </div>
  16. <div class="formbuilderform email_form">
  17. <div>
  18. <p>Using this form you can send me an email</p>
  19. <p>You must fill in all fields.</p>
  20. <p>
  21. Mails containing aggressive or abusive content will be deleted immediately. I do not intend to read them.
  22. </p>
  23. </div>
  24. <div class="required">
  25. <label for="fbrp__82">Your Email Address (Required Field)</label>
  26. <input type="text" id="fbrp__82" maxlength="128" size="25" value="" name="m6c9f9fbrp__82">
  27. </div>
  28. <div class="required">
  29. <label for="fbrp__83">Message Title (Required Field)</label>
  30. <input type="text" id="fbrp__83" maxlength="128" size="25" value="" name="m6c9f9fbrp__83">
  31. </div>
  32. <div class="required">
  33. <label for="fbrp__84">Message Text (Required Field)</label>
  34. <textarea id="fbrp__84" rows="10" cols="40" name="m6c9f9fbrp__84">
  35. </div>
  36. <div class="captcha">
  37. <img src="http://www.kardasa.pl/modules/Captcha/lib/gd_captcha/captcha.php?sess=CMSSESSIDed3334a6">
  38. <br>
  39. Type in code from the picture (Required Field)
  40. <br>
  41. <input type="text" maxlength="255" size="10" value="" id="m6c9f9fbrp_captcha_phrase" name="m6c9f9fbrp_captcha_phrase">
  42. </div>
  43. <div class="submit">
  44. <input type="submit" class="fbsubmit" value="Send message" id="m6c9f9fbrp_submit" name="m6c9f9fbrp_submit">
  45. </div>
  46. </div>
  47. </form>
  48. <!-- End FormBuilder Module -->
  49. </div>

As you can see there is nothing special about this form. What is important here is that this form is inside the uniquely named div tag called email_form. We will use it in our script.

But before creating the script we need to load the jQuery and jQuery Form Plug-in API. Add this two lines to your site head section after uploading API script files to your server.

<script type="text/javascript" src="/scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/scripts/jquery.form.js"></script>

Now it's a good time to add some kind of ajax loading indicator, to show it when your user is awaiting for his data to be processed. Mine is looking like this:

<div style="display: none;" id="form-indicator">
<span>Sending data in progress<br>
<img alt="" src="uploads/images/progress_bar.gif">

And here is the part of css style sheet which is handling the way that indicator will be shown to user.

#form-indicator {
	position: absolute;
	border: 1px solid #bbb;
	opacity: 0.7;

As you can see style=”display: none;”, makes our indicator hidden while the page is loaded. Our script will change it when the data will be send to server.

Now let us take a look at the script.

View the script source code
  1. $(document).ready(function(){
  2. var options = {
  3. target: '#email_form',
  4. success: function() {
  5. $('#email_form > #form-indicator').hide();
  6. $('#email_form > form').ajaxForm(options);
  7. },
  8. replaceTarget: true,
  9. beforeSubmit: function() {
  10. $('#email_form > #form-indicator').show();
  11. }
  12. };
  13. $('#email_form > form').ajaxForm(options);
  14. });

As always scripts using jQuery API are very short, i realy love jQuery for this.

Let us look at the script now. First line is saying that when the page will be ready it will fire up the defined function.

In the function we will construct an options object variable, which will take care of our Ajax forms behavior.

Target parameter will tell which part of our page should be updated and of course we wanted to be our email_form div tag.

The replaceTarget parameter will tell that our target should be replaced by server response.

The boforeSubmit will tell what to do before data is sended to server, it will be fire up when user will click on Send button on our form. And we are defining the functions which will show the user our ajax-indicator to let our user know his actions are being submitted.

The success parameter will tell what to do when the response will come from the server, and here we want to first hide the ajax-indicator. The second thing may be strange at the first moment but if you consider what may come to us as server response, you should understand why we are doing this. We may receive two things from the server an information that the email has been send or an error message and new form displaying user his submission errors. If the user will make some mistakes the server will display him the same form and we need to make sure our new form will also be ajax form. So we are using the jQuery selector which should select the form that is inside email_form div tag, and on this element we are calling ajaxForm to make sure this form will act as our Ajax form with defined options.

We are doing the same thing in the last line of the script. We are making our form an ajax form by calling the main method of API.

Of course you have to add the script into header section of your page:

<script type="text/javascript" src="/scripts/email_form.js"></script>

That's it, simple isn't it? Make sure you will read the API of ajaxForm it has other fancy and useful options that may help you. If you want to test it just use any one of my contact forms available on this site.

As you can see all I did in the front end is adding ajax-indicator as separate hidden div tag element, and some CSS lines to make it look nice. But there is other thing that has to be mentioned here. Normally the server response can return to us the whole page, and we don't want to load the header and footer of our page into email_form div. You need to make sure that your server will return not the whole page but only interesting partial in response to xmlHttpRequest. It can be easily done in any technology no matter is it PHP or Ruby On Rails. Just make sure you will do it in your back end, in the script that is handling the form submission. This is out of the scope of this article.

You can access the script I'm using on page on my svn server by following this link.



If you have found something wrong with the information provided above or maybe you just want to speak your mind about it, feel free to leave a comment.
All comments will show up on page after being approved. Sorry for such policy but I want to make sure that my site will be free of abusive or vulgar content. I don't mind being criticized just do it using right words.

Leave a comment

  • Posted on:
  • Author:
  • Comment:
  • 26.07.2012
  • Jakub
  • "Super":
    Szukałem, szukałem i nie mogłem znaleźć. Aż w końcu napotkałem się na wyjaśnienie krok po kroku jak to zrobić. Dzięki ;)