How to create an Ajax, validated form

Even on some very famous websites and blogs based on the WordPress platform, such as Smashing Magazine or Webdesigner Depot for example, the comment forms are not checked prior to submission. Which means that if the user hits the submit button without actually filling any information, he is redirected to the famous error: "Error: please fill the required fields (name, email).".

Thanks to jQuery and its plugins, it is possible to change the way those forms are handled, in order to obtain slick effects, and an overall better user experience.

In this tutorial, we'll associate the validation plugin, and the form plugin, to get a contact form that is validated before submission, and submitted via ajax. Why don't you give it a try?

Thank You for Downloading

I'm glad that you found my work useful. If you did, it might help some other people too. So why not helping me spread the word with a tweet? You could also buy me a coffee to thank me for my code and explanations if you prefer ;).
I hope you'll enjoy your download. Regards. Jeremy.

How to setup

Step 1: File inclusion

As this method works with jQuery, several jQuery files need to be included before we can move on, the jQuery library of course, the validation plugin, that will check that the required form elements are correctly filled in before submission, and the form plugin, that will handle the Ajax submission.
  1. /** jQuery Inclusion **/
  2. <script type="text/javascript" src="Path_to/jQuery.js"></script>
  3. /** Plugin Inclusion **/
  4. <script type="text/javascript" src="Path_to/jquery.validate.js"></script>
  5. <script type="text/javascript" src="Path_to/jquery.form.js"></script>

Step 2: The Form Markup

Once the files are ready to be used, we create the html markup of a very simple form containing 4 elements: a pseudo, an email address, a website and a comment area:
  1. <form id="comment_form" action="/postcomment" method="post">
  2.  
  3. <label for="pseudo">Pseudo</label>
  4. <input id="pseudo" name="pseudo" class="required" type="text" />
  5.  
  6. <label for="mail">Email:</label>
  7. <input id="mail" name="mail" class="required email" type="text" />
  8.  
  9. <label for="website">Website:</label>
  10. <input id="website" name="website" type="text" />
  11.  
  12. <label for="message">Message:</label>
  13. <textarea id="message" name="message" class="required"></textarea>
  14.  
  15. <input class="button" type="submit" value="Send" />
  16. </form>
As for usual forms, on submission, the data will be posted to the page specified in your action attribute, in our case, the page '/postcomment'. Please note that the class required has been added to each input that must be filled by the user before submission. If you wish to get more information about the validation plugin, you'll find some on its dedicated page.

Step 3: The Javascript Validation and Submission

In this particular case, the javascript is the place of main attention. The principle is quite simple really. As you can see in the following code, we setup the javascript validation, which means that every input having the class 'required' will be checked (line 2). Then, line 3, we change what happens when the form is submitted. Meaning, instead of having a normal submit, we'll have an Ajax submit (line 4):
  1. jQuery(document).ready(function(){
  2. jQuery("#comment_form").validate({ //Validation
  3. submitHandler: function(form) { //Event fired on form submission
  4. jQuery("#comment_form").ajaxSubmit(function(data){ //Ajax Submit
  5. jQuery("#comments_list").prepend(data); //Result display
  6. //You can clear the form at this stage if you want
  7. });
  8. }
  9. });
  10. });
After the form submission, what we need to do is to display the result to the user because as it is sent via Ajax, the page won't be refreshed and the data processing will be done behind the scene.

Step 4: The Ajax result

The result returned by the page '/postcomment' is held by the variable data (line 4 of the jQuery code). Knowing that, you can use your '/postcomment' page to retrieve the post variables as you would do for a normal page, for example:
  1. if(!empty($_POST)) { //Get the post values
  2. $comment_pseudo = htmlentities($_POST['pseudo'], ENT_QUOTES);
  3. $comment_mail = htmlentities($_POST['mail'], ENT_QUOTES);
  4. $comment_message = htmlentities($_POST['message'], ENT_QUOTES);
  5. $comment_website = htmlentities($_POST['website'], ENT_QUOTES);
  6. }
Because what you output here (as an echo for example) is going to be available in your javascript, you can choose between several formats to build the final result that will be showed to the user. The best practise option is to write a json array with the posted values:
  1. {
  2. "PSEUDO":"'.$comment_pseudo.'",
  3. "EMAIL":"'.$comment_mail.'",
  4. "MESSAGE":"'.$comment_message.'",
  5. "WEBSITE":"'.$comment_website.'"
  6. }
This json array will then be available in your javascript, where you can create the comment markup from it, and insert this markup in the page when ready. The jQuery code becomes then:
  1. jQuery(document).ready(function(){
  2. jQuery("#comment_form").validate({ //Validation
  3. submitHandler: function(form) { //Event fired on form submission
  4. jQuery("#comment_form").ajaxSubmit(function(data){ //Ajax Submit
  5. data = JSON.parse(data); // Get the json returned
  6. var comment='<div class="comment">';
  7. comment+='<div class="comment_msg">'+data.MESSAGE+'</div>';
  8. comment+='<div class="comment_footer">';
  9. comment+='From: <a href="'+data.WEBSITE+'">'+data.PSEUDO+'</a>';
  10. comment+='</div>';
  11. comment+='</div>';
  12. jQuery("#comments_list").prepend(comment); //Result display
  13. //You can clear the form at this stage if you want
  14. });
  15. }
  16. });
  17. });
As we've said, the variable data holds the result returned by the page '/postcomment', which in our case is the json array (line 5). From this array, we then write the html markup (line 6-11), and we insert it in the page (line 12). If you are not that at ease with json, it is still possible to write your html inside the postcomment page and to output it. It will therefore be all ready to go when reaching your javascript (remove line 5 then), but it's a slower option.

Summary

Creating an Ajax submitted form is actually very similar to how you would do normally as the jquery form plugin does most of the hard work for you. When a user will hit the submit button, the validation plugin will check that the required input are present and will leave the form plugin to handle the Ajax submission. You can then retrieve the post data as you would normally do and work with them to output the result to the user.

6 Responses to How to create an Ajax, validated form

  1. <><>

  2. Is this ajax??

  3. Around half a year before I redesigned my own organization site to
    have a style that was receptive.

  4. I blog frequently and I truly thank you for your content.
    This article has truly peaked my interest. I am going to take a note of your site and keep checking for new details about once per week.
    I opted in for your RSS feed as well.

  5. so useful in one article, sorry I did not find your site before. Thanks for the work you've done

  6. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Useful Resources

Scroll to Top jQuery plugin illustration

If you happen to have on your site some pages that are a bit long, and therefore will lead your users to scroll down quite a bit to read your content, they may not have the patience to scroll again to get back up to the top. That's where this little plugin, hand made by NOE interactive comes in handy. Just put it on your website, and it will help your users get back to the top of pages with a single click, and with a small smooth animation (how nice is that :) ).

In this article featured on NOE interactive, you'll learn how you can install the jQuery plugin on your website. There's a complete step by step guide as well as a demonstration. If you wish to download the plugin, it's also hosted on Github.

Read more
How to turn any jQuery plugin into a WordPress one illustration

WordPress and jQuery are both very famous for their plugins. In the case of jQuery, plugins allow developers to extend the library's capacities in order to create beautiful effects. In WordPress, they allow anyone to benefit from the work of others, as they come under the form of a module that you can easily activate from within the administration interface, and start using right away.

Creating one of those modules is not that difficult, but if you are not familiar with their syntax, it could end up being a headache. There are many jQuery plugins that have been transferred into a WordPress one already, but what can you do when it is not the case? How do you do when you have found the perfect jQuery plugin for your latest site, but it is not yet available as a WordPress plugin?

In this tutorial, we'll see how you can easily create a WordPress plugin from a jQuery one. We'll review what a jQuery, or a WordPress plugin is actually made of, so we'll find the elements they both have in common. From there, we'll show how it leads us to perform some simple operations to allow us to benefit from our jQuery plugins in a WordPress template.

Read more
How to integrate your instagram pictures with php illustration

Ever looked for a straightforward way to integrate you instagram pictures on your website? Without a plugin nor an iframe? Well this article featured on the NOE interactive's blog presents how you can do so with PHP.

It's a neat and simple solution that uses the instagram's API to get a particular users' latest pictures, and then display them in a ul list.

It is accessible to most developers as it is a "personalize, copy and paste" kind of solution. Just two steps are required, configuration, and implementation.

In this article featured on NOE interactive, you'll learn how you can install the solution on your website. There's a complete step by step guide as well as a demonstration. If you wish to download the solution, it's also hosted on Github.

Read more
@schlessera @github Ho yes @github. @schlessera is right. That’s a common use case. Can we have it please?21 Apr / 16:20