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
  • Dennis

    For me, this code did not work at all until I enclosed it within a document.ready function.

    $(document).ready(function() {

    });

  • Pingback: Submit A Form Without Page Refresh using jQuery

  • http://mycashloanstoday.co.uk/ cash loans today

    this image is certainly the special. Full Article

  • http://www.tuljabhavani.in Kedar

    I just wanted to know How to Validate URL’s?

  • http://ikincielesyaalanlar.ws/ ikinci el eşya

    very very very thank bro.
    great contact form :)

  • Pingback: 13 Effective Free jQuery Plugins that Enhance Your Forms | Free and Useful Online Resources for Designers and Developers

  • Concerned Citizen

    This is some of the worst JavaScript I’ve seen. Your selectors are terrible ($(‘div#foo’) instead of $(‘#foo’)), you copy-paste code all over the place, you return false instead of preventing the default action alone, you manually concatenate your data string instead of using the JSON library, you compare things with “==” instead of “===”…. This is just awful style and being a novice.

    • Jonas Lindström

      Your criticism is warranted but your tone is not. Instead of complaining, you could thank the author for providing a simple, clear and well documented solution that anyone can understand. You could then add that there are still improvements to be made and list those specific improvements (at least you listed some). If there is a better tutorial on the web, please link to it. If there is not, why the harsh tone? It seems to me like this is a very good starting point but it can still be refined.

      A big thank you to the author from me – this is still tremendously useful approaching 2013.

      • Brian T.

        Sorry I have to agree with Concerned Citizen. You say its rude and easy for “anyone to understand.” There in lies the problem. A novice user could possibly come here and see this jQuery code and think it’s an acceptable way to code. It’s not. Specifically the prevention of default actions (rather than returning false). This is really not good practice in code and can cause serious issues down the road.

        Providing free resources is always encouraged and appreciated online… however one needs to understand the idea of doing more harm than good. Furthermore any self-respecting programmer wouldn’t want to publicly put bad code online and list it as their own.

      • jackstrummer

        I have to agree with Lindstrom. Criticism is fine but insults are not, namely: ‘…being a novice’, ‘…any self-respecting programmer…’ If you’re having a bad day, take it some place else. As Lindstrom points out, state your refinements to the code and move on. You both mention the prevention of default actions, so instead of being so disparaging of someone else’s efforts, explain what you mean, and bother to write in a little code to demonstrate. Politeness costs nothing, and will say more about you in the long run than anything else you accomplish in life, codewise or other.

      • Rimple Saini

        Thank you so much for this tutorial. It has been proved so helpful to understand basic.

    • JeffWay

      You have to remember that this article was written a very long time ago. All of those best practices that you speak of weren’t as widely known back then.

      • RachelK

        Hi Jeffrey – what are the chances you’ll update this tutorial? And can you also add in the process.php details too? cheers

    • gavin

      So could you be so kind to submit a php form tutorial with ajax and jquery that is done the right way, seeing that you have so much to say about this tutorial. It’s one thing to critisize someones work but a whole other ball game to take te time and write a tutorial to show all our new php guys what is the correct way of doing it.

  • sachin

    jhkjhjhjkhjjoiioui

  • Pingback: 我收集到的最新的AJAX教程和技术(上篇) « 成人免费资源三级分享网站

  • web tasarım

    If you want to take advantage of our designs if you need to contact us.

    • ger

      thanks

  • emj

    How do I get it to send an email to me when someone submits the form? I edited the process.php file and added my email address, but I still don’t get anything when the form is submitted.

    • emj

      I entered my email address for: $to, $email, $fromaddress, and $mail->From.

  • Rac

    this is such the best article of using jquery with ajax, thank you for your time so much I learned so many thing from this article.
    I just have a question how can I check the return result if some thing error like cannot connect to database something like that?

  • Ash

    The ajax section does not work with the latest version of jquery, any ideas on how to make it compliant?

  • Ge

    thanks

    • ge

      the best

  • artun ykare

    Thank you, very clean explaination!

  • test

    test

  • abdelrahman noural

    thanks , this is very nice , but how can we upload file by this form ?

  • delcore92

    Any Php to go with this tutorial??

  • Marcel M.

    hello friends, thanks for this code, but my problem is the charset .. all special character will be return with ??? this. I want to transfer my form fields in the UTF-8 charset for the Swiss-German-language

  • Mahesh

    I nice article that explains the JQuery Ajax succinctly!

  • AlBundy

    Your doc was really helpful for me.
    Thanks to you, I have successfully performed my first ajax form.

  • pietro

    thanks!

  • Chris Frank

    This is how you validate email:

    function validateEmail($email){
    var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
    if(!emailReg.test($email)){
    return false;
    }else{
    return true;
    }
    }

    $(function(){
    $(‘.fail’).hide();
    $(“.submit”).click(function(){
    var email = $(“#email”).val();
    if ( !validateEmail(email)){
    $(‘.fail’).append(“Please enter email”);
    $(‘.fail’).show();
    $(“#email”).focus();
    return false;
    }

    • Alo

      Hola

      • a

        testing comment system

      • a

        Hoy

      • hoya

        HOya

  • http://www.facebook.com/krrishnaNanKadavul Krishna Rao

    awsom,./

  • Shubham

    Really nice work…….thank you…

  • http://www.facebook.com/bruno.dilhof Bruno Dilhof

    Thanks for this tutorial!

  • http://www.facebook.com/profile.php?id=764338584 Brad Guy

    How do you add check boxes or radio buttons to it?

  • thankful

    thank you… concerned citizen is an idiot. jerks like that make everyone else’s life more dificult.

  • legomez

    Love this tutorial, but how I can return any values back from bin/process.php in the case that I need to troubleshoot what is happening in the process.php file. Someone can help me with this?

    • http://www.filentrep.com Adrian Domingo

      You can test the process.php independently. Instead of using ajax, do the traditional way of doing a php form.

  • sai

    Thanks very usefull for beginners.

  • http://twitter.com/AftabKhalid Aftab Khalid

    you did not focused about process.php, why?

  • Vijex

    Thanks for this tutorial!

  • http://www.facebook.com/peter.hayman Peter Hayman

    This is wonderful! Thank you, Sir!!!

  • zaibishah

    Gr8 tutorial very much descriptive and easy to understand. Would be even better if picture’s background is also mentioned in code.

  • kjkjkjkj

    kjjkkjkj

  • Agoagogo

    Thank’s so damn helpfull.

  • Natalia

    Excelent Post!
    I have a question, How you can validate 2 differents forms on the same page using js.

    • http://www.filentrep.com Adrian Domingo

      2 options:
      1) you just have to change url: “bin/process.php” in the code for the second form. create 2 different process files (process1 and process 2 or whatever you want to name it. :) ).
      2) OR add another value to the datastring and use that in an IF statement in your process.php file.

  • json explorer

    what I would like to see and did not see in this tutorial where json might be used exactly.

  • http://www.filentrep.com Adrian Domingo

    I had this tutorial on my tabs list for the longest time. I finally got around to actually trying it out. Fantastic post. I just used a “return true” on my process.php for trying it out. :)