Everything Photoshop Subscribe

Submit A Form Without Page Refresh using jQuery

In Javascript / AJAX by Eric

Previously on NETTUTS, Philo showed how you can use jQuery to add form validation to wordpress comments that works without any page reload. Another great way of utlizing jQuery to enhance user experience is to not just validate, but to submit your form entirely without a page refresh. In this tutorial I'll show you how easy it is to do just that -- submit a contact form that sends an email, without page refresh using jQuery! (The actual email is sent with a php script that processes in the background). Let's get started.

The Demo

In this example, we have a simple contact form with name, email, and phone number. The form submits all the fields to a php script without page refresh, using native jQuery functions (native meaning, you don't need to download any extra plugins to make it work.

If you have found this article without any prior familiarity with jQuery, a great place to get started would be Jeffrey Way's article on 15 Resources to get you Started with jQuery From Scratch.

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>
  

You might notice that I have included a div with id contact_form that wraps around the entire form. 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
    });
  });
  

What the first function() does is, it loads the events inside, as soon as the html document is ready. If you have done any work in jQuery previously, the function is the same as jQuery's document.ready function. So we start with that, and inside we have our click function that executes on clicking the submit button with class name of "button". Ultimately what we have accomplished with these lines of code is the same as if we were to add an onclick event to the submit button in the html. The reason we do it with jQuery is for clean separation of our presentation from our scripts.

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;
      }
      
    });
  });
  

Inside our function that loads when the page is ready, we add some form validation. But the first thing you see that got added is $('.error').hide();. What this does is hides our 3 labels with class name "error". We want these labels to be hidden not just when 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();
  

We then check if that value is blank, and if it is, we use jQuery's show() method to show the label with id "name_error":

  if (name == "") {
    $("label#name_error").show();
  }
  

Next, we place the form focus back on the input field with id of "name", and finally return false:

  if (name == "") {
    $("label#name_error").show();
    $("input#name").focus();
    return false;
  }
  

Be sure to have return false in your code, otherwise the whole form gets submitted (which defeats 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;
  

We have a lot going on here! Let's break it all down - it's so simple and so easy to use once you understand the process. We first create a string of values, which are all the form values that we want to pass along to the script that sends the email.

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();
  

We can use that 'name' value again, as well as the 'email' and the 'phone' values, to create our dataString:

  var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
  

I've commented out an alert that I sometimes use to be sure I am grabbing the right values, which you may find helpful in the process. If you uncomment that alert and test your form, assuming everything has gone right so far, you should get a message similar to the following:

Now we get to our main ajax function, the star of today's show. This is where all the action happens, so pay close attention!

  $.ajax({
    type: "POST",
    url: "bin/process.php",
    data: dataString,
    success: function() {
      //display message back to user here
    }
  });
  return false;
  

Basically what's going on in the code is this: The .ajax() function processes the values from our string called dataString (data:dataString) with a php script called process.php (url:"bin/process.php"), using the 'POST' method (type:"POST"). If our script processed successfuly, we can then display a message back to the user, and finally return false so the page does not reload. That's it! The entire process is handled right there in these few lines!

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;
  

Then we used jQuery's ajax function to process the values in the dataString. After that 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;
  

The success part of the script has been filled in with some specific content that can be displayed back to the user. But as far as our ajax functionality goes, that's all there is to it. For more options and settings be sure to check out jQuery's documentation on the ajax function. The example here is one of the simpler implementations, but even so, it is very powerful as you can see.

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>");
  

What that has done is replaced all the content inside the contact_form div, using jQuery's html() function. So instead of a form, we now just have a new div inside, with id of 'message'. Next, we fill that div with an actual message -- an h2 saying "Contact Form Submitted":

  $('#message').html("<h2>Contact Form Submitted!</h2>")
  

We next add even more content to the message div with jQuery's append() function, and to top everything off we add a cool effect by hiding the message div with the jQuery hide() function, then fade it all in with the fadeIn() function:

  .append("<p>We will be in touch soon.</p>")
  .hide()
  .fadeIn(1500, function() {
    $('#message').append("<img id='checkmark' src='images/check.png' />");
  });
  

So the user ends up seeing the following after they submit the form:

By now, I think you will have to agree that it is incredibly easy to submit forms without page refresh using jQuery's powerful ajax function. Just get the values in your javascript file, process them with the ajax function and return false, and you are good to go. You can process the values in your php script just like you would any other php file, the only difference being that the user does not have to wait for a page refresh - it all happens silently in the background.

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.

Demo & Source

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!

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.

 

Enjoyed this post? Your vote is always appreciated!! Delicious StumbleUpon Float Digg

Comments

Leave a Comment
  1. Very nice, thanks a lot.
    I’m gonna give it a go ;)

  2. the demo looks very good.
    I will try it today along with my PHP form processor….
    Thx and cheers,
    Sanjay

  3. Thats cool, I have used plugins for wordress a lot, but I do enjoy a good read!

  4. var name = $("input#name").val();
    var email = $("input#email").val();
    var phone = $("input#phone").val();
    var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;

    is the same than


    $("#contact_form form").serialize();

    Good tutorial.

  5. good one. i am using a this technique a lot.

  6. Nice work, but i think you missed to check your styles, the submit button is not shown properly in IE 7

  7. Exactly what I’ve been looking for I can’t thank you enough! Love the site, I wait impatiently for every new addition!

  8. var dataString = ‘name=’+ name + ‘&email=’ + email + ‘&phone=’ + phone;

    VS

    $(”form”).serialize();

  9. Very nice, but I have two problems with your solution, one technical and one fundamental:

    * There is nothing to indicate the data is being submitted to the server while waiting for the reply. The submit button should be disabled while waiting for the Ajax return, else you will allow the form to be submitted several times.

    * This solution will not work without JavaScript. You may say that everyone that matters has enabled JavaScript in their browser, but more and more people are browsing internet on their phones, PDA’s, webtops, game consoles, MP3 players, etc, and then you just cannot count on stable JavaScript support.

  10. Gravatar

    Mark Bowen

    Hiya,

    There are some very nice tutorials on here of late but it would be really nice if the Javascript versions worked without Javascript enabled too. Shouldn’t be too hard to do but I’m just thinking that if people do come to your site without Javascript enabled then the form isn’t going to operate correctly for them. Just a thought though.

    Nice tutorial anyway though.

    Best wishes,

    Mark

  11. Nice and simple, and does exactly what is needed an no more, perfect :) Thanks!

    @Mark Bowen - the action on this form is set to nothing, so if there was no JS enabled it would submit to itself. It’s easy to pop some PHP in the top of the page checking for a submission and then processing the form if needed, including showing error messages.

  12. Nice tutorial. I’m just thinking about using this script for posting comments on my blog, but then I’ll get some SEO issues if comments are called through Ajax.

    Using it for contact forms is very nice though ;)

  13. guillaume: why not just use this form method to put the comments into your database, and then use a non-ajax system such as php to display them. That shouldn’t give any SEO issues should it?

    Great tutorial!

  14. Hey, nice tutorial. Personally I’d do all the validation on the server side, this saves you from doing it twice (client AND server side). You can also use jQuery’s serialize function (http://docs.jquery.com/Ajax/serialize) to process all the form inputs for sending data to a server. This way if you add more form fields the javascript will be able to cope without modification.

    James

  15. disable the submit button when u submit…

  16. need to add in some ../ into the css file so the images in the css are at the right level as is it doesnt show the images!

    Thanks for the tutorial contact forms have always been a headache for me!

  17. Nice tutorial - I agree with Mark though that for users without JS enabled, it’d be great to present an alternative. I went to a presentation by Jeremy Keith (adactio.com) where he talks about his HIJAX method of using ajax which basically intercepts the form details IF javascript is present, and if it isn’t, processes the form in the normal way.

    That’s not to take anything away from this great tutorial or this wonderful site - keep up the good work!

    David

  18. Nice tutorial. My only (small) comment is that I’d prefer to see all fields failing validation to be shown at once, rather than one at a time.

    That’s a small niggle and one that’s easily fixed.

    Thanks for posting the tutorial.

  19. nice tutorial, very useful! thanks a lot.

  20. What is missingin this nice demo is the ajax_loading gif that will notice the user that the action is ongoing, rather than nothing, with peep clicking like crazy on the sending button.

    very nice and i’m going to use this a lot!

  21. Very Nice Tutorial. I am going to use this tonight on my personal website.

    Thanks!

  22. This what I looking for, thx’s

  23. I take it we’re above progressive enhancement, eh? A form without an action and the validation event attached to the submit button’s click?

    These are dangerous practices to be teaching in a tutorial.

  24. It is very useful script.

    Thanks a lot.

  25. This will come in very handy. Thanks

  26. I have to agree with Michael Thompson. Using AJAX to submit the form is great, but doing it without a non-javascript fallback is terrible practice (and means that non-JS users can’t contact you… which could cost you or your client money).

    If you really want to do it right check out the jQuery Form Plugin. Its based entirely around progressive enhancement, and gives you callbacks for beforeSubmit (for validation), success, error, etc.

    Disclaimer: I am not affiliated with the above plugin, but I’ve used it extensively on projects for Enterprise Level clients.

  27. @Michael Thompson

    A form without an action will post to itself - nothing wrong with that… especially as this is a demo so the form isn’t getting posted anyhow. Whats wrong with validating with the submit button’s on click?

  28. This is good one.

    Thanks
    http://www.toputop.com

  29. really nice, thanks again
    i’ve checked it all…i’m in holidays so when i come back i’m goint to run my hands
    adeux!

  30. realy nice tut and thank alot.

    BUT! when i use opera and i click the submit button fast five times then in the confirm page i get five green circles with V in it in sted of one just saying but i dont know if this is a error or not

    but thank a lot for the tut again :D

  31. nice tut. again, u should always make a complete tutorial about taking care when JS isnt enabled too though.

  32. Gravatar

    Barndizzle

    I experienced the same issue as Snorri3D. I think it would be simple fix to deactivate the submit button after it is clicked. Details….nice tutorial.

  33. Keep in mind that is more a demonstration of technique, not a live, working application. Trapping for the condition of JS not being on is something that can always be added later.

    LOL at Snorri3D. Sounds like something that’s going to happen a lot :)

  34. Useful

  35. What if I want to have submitters also upload a file. How would that work?

  36. @ben griffiths
    The click event on the submit button isn’t the only way a form can be submitted. Hitting the Enter key while in a text field also submits a form. It’s best to do form validation as well as the AJAX post on the form’s submit event.

  37. Very cool, looks good too!

  38. thats ok, but…. what if an error occur on the server?? what if the MSG never send?? the confirmation message should be return by the server!!

    have funnnnn ;)

  39. Gravatar

    Monkeytail

    Sieht gut aus.. nice tut!

    question:
    what’s the difference between html() and append() function?

    from code:
    $(’#message’).html(”Contact Form Submitted!”).append(”We will be in touch soon.”)

    .. why first html() and then append() and not twice html or append

  40. I have been waiting for this for a long time!!!!

  41. Looks fine, looks like it works great. I like the not having to refresh. And crysfel has a good point.

  42. Another nice tut! Gotta love that AJAX!

  43. BTW Collis!
    I got a wordpress blog now! I got it for ha.xors.org which will be my personal blogging site, so keep them wordpress tuts coming ;)

  44. hmmm, I like the tutorial overall, but I have some issues with some stuff:

    Firstly, you shouldn’t be attaching the ajax to the click event of the button, you should be attaching it to the submit (”onsubmit”) event of the form. Also, that green-tick image should be preloaded. Also, don’t use underscores in your ID names - older browsers don’t like this. And what is the point in appending the “we’ll be in touch soon” message if ur just gonna hide it a split second later- it doesn’t even appear for the user to read it! The worst thing about this tutorial is that it does not degrade!!! - This is a big issue!

    @David - You don’t need an entirely different method/framework/technology (hijax) in order to make the enhancement unobtrusive.

  45. Gravatar

    Philsbury

    Shane mentioned he’d like the validation show at once. If you use jQuery’s jquery.validate plugin you get that to happen. I’t also far fewer lines of code! Otherwise very nice tutorial

  46. Great tutorial as always. In case anyone decides to go the plugin route there is an excellent Form Plugin for jQuery that I have found to be a great resource if you are going to be using this method for a lot of pages on your site:
    http://malsup.com/jquery/form/

  47. Thanks so much for this great tutorial. I am hoping that one day I will adopt jQuery and this will be very useful.

    I need some help to understand how someone can use jQuery such that when the page is submitted, it is validated and then the person can be redirected to another page e.g. wen someone is trying to login, I can validate the empty fields, check and validate the credentials and then someone is directed to another page instead of just replacing content in a div. I already have the scripts running though I have still failed to understand how to use jQuery in this respect.

    I will be very grateful for the help and thanks for the great tutorials you are posting.

  48. I have written a similar article, AJAX Forms with jQuery that discusses creating a form that works with or without JavaScript.

    A couple of things that I suggest is to instead of having the error messages already present in the markup on the page, just append them with JavaScript. Also, I think a more descriptive error message would be better. Instead of saying “This field is required”, provide a better error message. Like, “You forgot to enter your email address” or “Your email address is invalid”. Just my thoughts.

  49. Thanks for this, It’s nice and simple. :)

  50. I love it very lovely flow right there thank you for sharing this one.

  51. Hey everyone! Thanks for all the gracious comments regarding the tutorial. It’s just so easy to submit forms with jQuery and ajax so you don’t get a page refresh. The possibilities seem limitless and I’m glad if I can help others get started with these techniques.

    Some of you have mentioned what is lacking in the tutorial, namely lack of support for users without javascript. I think you guys are absolutely right to mention that problem, and I definitely recommend taking care on this issue when you publish this kind of form to a live site. I would probably go with Ben Griffiths’ solution to put a php script in the contact page itself which checks for form submission and processes it if so.

    I see a couple recommendations for the Malsup form plugin - I have yet to give that one a try! Looks like it handles precisely these issues being discussed.

    Also thanks to James for mentioning not to put underscores in your ID names due to problems with older browsers not recognizing those.

    @Monkeytail - the html() function replaces whatever is inside the current div. The append() function does not replace anything, instead it adds on to the end whatever you currently have inside the div.

    @Matrich - have you considered just using window.location to redirect a user to another page? Perhaps you could place that within the success part of the ajax function.

  52. Mine did not work I do not know what I am doing wrong :(

  53. Gravatar

    joelrthomas

    This is a very nice tutorial, the end result is incrediblly useful. I am wondering if someone could help me figure out how to integrate this with my existing forms. I have them posing to a .jsp page and my fields also have different names such as “Contact0FirstName” as apposed to “name”.

    Any help would be greatly appreciated, thanks!

  54. Awesome. It’s very useful.

  55. Excellent! nice work!

  56. hi , am ashok i need the code in javascript rather than in PHP. plz send me the code in javascript

  57. Great work! I learned a lot!

  58. nice tuts!!!

  59. In the readme.txt you are talking about some chances i have to make to get it work. In process.php i have to change $to, $email, $fromaddress, and $mail->From. I don’t know what information I have to put here. I’m a noob sorry:).

    $to = ’someone@example.com’;
    $email = ‘email@example.com’;
    $fromaddress = “you@example.com”;
    $mail->From = “mail@yourdomain.com”;

    I chance it al to info@slagersworst.de but it isn’t working…

  60. awesome.

    and now how do we get that into wordpress as a plugin :)

    great work!

  61. That’s cool, check out this mobility scooter I bought my mom for Christmas.

    http://www.travelscoot.com

    It is called TravelScoot mobility scooter and it folds up like an umbrella and weighs just 35 lbs. She keeps it in a carrying bag in her trunk. She takes it out anywhere.

  62. It’s is not very good form - user don’t see progress bar when he click on button :(

  63. very informative

  64. Bad. In demo email fileld not check. I write ‘testtest.com’ (not ‘test@test.com) and form was submit succes. 2author: if you create a tutorial for noobs do it as professional.

    // sorry for my English - I am from Ukraine and my English is bad.

  65. Great tutorial, thanks! How do I integrate some radio button values and check boxes into the form and have them emailed as well? I’m kind of new to PHP and javascript and can’t seem to find a good tutorial on how to get that part of my form working.

  66. 1. Does not check for valid email address

    2. Phone field allows you to Input a number

  67. Awesome tutorial, very descriptive, step by step guide as to whats going on, all thats left is to see if it works!!

  68. Have a question. :)
    How can I put a simple iteration if-else in the returned messege?
    For exaple, if my process.php does a control in a registration form - maybe for an already existing registered user - how can it comunicates this information to the ajax function and then change the returned messege?

    Sorry for the bad English, I’m Italian :)

Add a Comment

Note: We use Gravatars on NETTUTS, they are little icons that appear next to your name on this site and on many others. You can get a Gravatar account for free and any other site that supports it will show your avatar too!

 

Trackbacks

Leave a Trackback