Try Tuts+ Premium, Get Cash Back!
Submit A Form Without Page Refresh using jQuery

Submit A Form Without Page Refresh using jQuery

Tutorial Details
  • Difficulty: Intermediate
  • Estimated Completion Time: 2 Hours

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.


What We’re Building

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.

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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: 30 Fresh AJAX Tutorials And Techniques : Ajeesh @ CyberBeams

  • http://www.mustlovepink.com Jillian

    I can’t get this to work! I’m trying everything I can think of, but it won’t work. Please help!

    • Neil

      @Jullian – what part does not work for you? Can you be more specific?

    • Rebin

      hi,
      i dont think this is actual form submit. this is just a request with query string. what if i have 30 fields inside my form? should i get all that and put it in query string?

  • Marlyn

    can you please share the source code? i can’t get it.. :(

  • http://aykak.com Aykak

    nice Tuts like always… I need a little clarification how to use this method with Smarty templates …

  • http://dir.azzazianesthesia.com Said Bakr

    Hi,
    All ajax submit tutorial regards success, but where error or fail?

  • http://www.sstudio.me Web dizajn Crna Gora

    Very nice.

  • http://kjventura.com Kevin John Ventura

    Thank You! Very Nice!

  • Pingback: Contact Us WebFom validation using Java script

  • MARY

    nice and simple.
    Can i use the ajax part to submit any other jQuery form?
    of course to change the dataString var also.

    anyone could help.

  • http://www.indievision.com Tony Elwood

    Thanks for the clean contact script. I’ve got the form built, but can’t seem to get the PHP to play right. PHP is rather new to me, I’m wanting the senders info to come to me. Where on which php file should I put my email address…sorry, I’m just getting into doing this php thing. My site is not a wordpress…it’s html5…would that be an issue?

    Thanks so much.

  • Alex Strauss

    IIt doesn’t work! Email didn’t send!

  • Kunal

    Very cool tutorial. I am trying to get this working with java backend, and I have a weird thing going on in spring 3.

    If I shut off tomcat, the text div refreshes fine, but if I keep tomcat on but return nothing in my controller it never updates the form div.

    Any suggestions?

    Thanks!

  • Benn

    Great Tutorial. Is there a way I could use this to create multiple forms on one page??? I have a loop making a number of forms for a page but everytime I submit it just takes the first forms values….. Any help??

  • http://pisolutions.in/Contact.html Tom George

    Please help me

    All data typing after submit button Click then going this mail id “riteshudupak@hotmail.co.in”

    How to do this one? please help me!

  • http://www.wickswebdesign.com Anders

    I love this tutorial! Great job. I do have one question though. When people submit my form, the browser scrolls to the top of the screen. This defeats the purpose of the fade effect because people miss it :P Is there a way to keep the browser from moving? Thanks!

  • http://localhost Ghora

    WTF is this shit?
    Use $(‘#form’).serialize() it will return all form parameters in query string format.

    • Jerry Lanphear

      Indeed, that would work sometimes.
      However, using query string is not for every case. You have to decide if it is appropriate.
      For instance the data being posted might exceed natural limits for number of characters on a query string. The data being posted may contain proprietary information like a password or other security measures. The data being posted may indeed be not serializable.

      There are many ways to do this.

  • http://www.annkwilinski.com Ann K

    Thanks for posting this tutorial. I did some adjusting to the process.php file but it works great for what I need.

    -Ann

  • M

    Hey, Thanks for nice script. I was wondering can I use this script for multiple forms on one page? If yes – how should I use it?

    Thanks!

  • bfs

    For those having trouble getting radio buttons etc… to work, look at the $(“#contact_form form”).serialize(); info by anieto2k on the first page of comments. That does the trick.

    -bfs

  • Julio

    Where do I input my email address to the information?

    $recipient = ‘your_email@example.com’;

    • Julio

      I don’t know where to place my email address to receive the input information. help.

      thank! – Julio

    • George

      Please where will I put my email address: Please I need help, I don’t know where to put my email address:

      jQuery(function() {
      jQuery(‘.error’).hide();
      jQuery(“.button”).click(function() {
      // validate and process form
      // first hide any error messages
      jQuery(‘.error’).hide();

      var name = jQuery(“input#name”).val();
      if (name == “”) {
      jQuery(“span#name_error”).show();
      jQuery(“input#name”).focus();
      return false;
      }
      var email = jQuery(“input#email”).val();
      if (email == “”) {
      jQuery(“span#email_error”).show();
      jQuery(“input#email”).focus();
      return false;
      }

      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if(!emailReg.test(email)) {
      jQuery(“span#email_error2″).show();
      jQuery(“input#email”).focus();
      return false;
      }
      var website = jQuery(“input#website”).val();
      var subject = jQuery(“input#subject”).val();

      var msg = jQuery(“textarea#msg”).val();
      if (msg == “”) {
      jQuery(“span#msg_error”).show();
      jQuery(“textarea#msg”).focus();
      return false;
      }

      var dataString = ‘name=’+ name + ‘&email=’ + email + ‘&website=’ + website + ‘&subject=’ + subject + ‘&msg=’ + msg;
      //alert (dataString);return false;

      jQuery.ajax({
      type: “POST”,
      url: “process.php”,
      data: dataString,
      success: function() {
      jQuery(‘#contactform’).html(“”);
      jQuery(‘#message’).html(“Contact Form Submitted!“)
      .append(“We will be in touch soon.”)
      .hide()
      .fadeIn(1500, function() {
      jQuery(‘#message’);
      });
      }
      });
      return false;
      });
      });

  • http://shoveit.com pat rafter

    Dont bother downloading this, it doesn’t work and will waste your time.

    • http://weebuild.biz Nathan

      Dude, I really hope that you know that this JavaScript doesn’t actually submit the form (there is no such thing as JavaScript that submits a form) and that you need PHP to submit the form. This JavaScript just makes form submitting 100 times better, but you still have to use PHP to submit it.

      • http://www.daemonmasters.com Karl Bateman

        There is a way to have Javascript process the form using node.js, this however would be beyond the scope of this tutorial. AJAX is an awesome way of submitting forms without page refresh. Great tutorial!

  • VEL

    Thank you very much,your demo code is very useful for me …..

  • http://brm.sk 81403

    There’s an easier way of submitting a form via ajax. You don’t have to manually build the query string (dataString = ‘name=’+ name + ‘&email=’ + email + ‘&phone=’ + phone), just use jQuery’s serialize() function:
    dataString = $(“form.contact”).serialize();

    See http://api.jquery.com/serialize/

  • Prateek Sasanker

    Can we use the same method for dropdownlists ?

  • mukesh kumar sharma

    Can i use Ajax for a multi data transfer between a form.

  • http://www.coursesweb.net OnLine

    Hy,
    For more compklex forms, with multiple fields, you can use the Validator plugin, documentation: http://docs.jquery.com/Plugins/Validation

  • Kripte

    Thank you friend.This is a awesome tutorial.

  • http://www.mantolamacatizolasyon.com mantolama

    In this example, we have a simple contact form with name, email, and phone number.

  • depe

    And what if the email function fails?
    Is there any way to get a notification back to the user, that the contact form hasn’t been successfully sent?

    • http://www.johnshammas.com John Shammas

      You can’t use anything like if ($mail), but you can check if there was a timeout error or an error code. So, in your PHP file, tell it to pass a 404 or something of the like to the headers when the email does not go through; jQuery will see the error in this way. http://api.jquery.com/jQuery.ajax/

  • soumya sanjeev

    very nice and really simple!!!!…

  • samreen

    Code is nice but there is email validation missing, along this should also check the email format.

  • Mike Laird

    A much more useful tutorial would be to show how to use the jQuery plug-in called Validation. It is used on hundreds of sites, including major sites like cbs.com — and it has been localized into 37+ languages. Why build this little thing? How about writing a tutorial that shows step by step, how to do the same things as above, and more, using the Validation plug-in. That would be good teaching and a good contribution to getting lots of useful web sites built all over the world.

  • Pingback: An idiot’s guide to AJAX: forming POST data properly | Wiflufu

  • http://www.sonetinfotech.com Sudhakar

    Hey thak you very much for providing good codes to learn.

    I need a code which should fulfill the below criteria.

    insert an image from a HTML form into the database using ajax Backend should be Mysql. Front end is PHP.

    I will wait for this post if any one de for this please send a copy to my mail id too. My mail Id is

    ssr.sudhakar@gmail.com
    sonetinfotech@gmail.com

  • evans

    How do I redirect to /bin/process.php?url=registration, and /bin/process.php?url=contact, using jquery’s ajax function? I am trying to use the same js script for both forms (i.e. registration and contact)

  • Drakinfly

    Awesome script, can I use it with other php forms?

    Where do I add my email address to receive the emails?

  • usman

    Hey i want to put a custom header how can i do that thanks in advance

  • qaz

    hello experts .. this is nice code … i am using it .. its work fine in firefox .. but not work in IE 7, chrome ..
    can any body help me for this

  • http://www.konutprojeleri.com.tr konut projeleri

    That would be good teaching and a good contribution to getting lots of useful web sites built all over the world.

  • Pingback: Top 10 Jquery Tutorials you should know « « WebDesignerGeeks - Web Designer, Web Developer blog WebDesignerGeeks – Web Designer, Web Developer blog

  • http://www.topdown.me topdown

    Thanks very much, Helped me make the site a bit faster :)

  • igo

    can you help me?
    i want to make a load partial in rails 3..
    but i can not make it.

  • rezvie

    how about uploading a file using this example

  • http://www.jacquesmaes.be Jaakie201

    Thanks for the tutorial.

    I also had a lot of trouble for the email to be sent since this is all a bit new to me, managed to get it to work though with a newer phpmailer file and updated process.php. For all the ones with the same problem: http://home.euphonynet.be/jaakie201/other/bin.zip

    • Chris

      Thanks Jaakie – worked great!

    • http://www.unicora.com Mark Searle

      Great work with the tutorial, obviously its got a few bits that really could do with an update but very helpful! Jaakie201 provided the fixed process.php and I can confirm it is working.

    • http://danielfraserwebdesign.com daniel fraser

      Jaakie you are my saviour!! Thanks so much

  • http://www.q-dent.es/jquery/tutorial.html carlos

    it doesnt work!!!
    It says that all is succes but i dont received the mail. whats the problem?
    i have completed with my email, TO, FROM… but it doesnt work

  • JRS

    I would recommend use of the serialize() method it will automatically create what in the tutorial is called dataString – a URL encoded text string. In this tutorial $(‘form’).serialize() will produce the same as the dataString construct. This requires less coding and is quicker to replicate.

  • http://bintangweb.com Bintang

    Great tutorial as always.
    I am a newbie on JQuery, this really help me a lot.

  • Pingback: Ajax and Jquery Technics Resources « Free Download Image Pattern Theme Wallpaper Box

  • Jagan

    Nice Tutorial.
    Can explain how to upload a file using this example.

  • Pingback: 45 jQuery Plugins And Tutorials To Enhance Your Forms