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
  • http://negbox.com/ Slave Rat

    Nice tutorial. I’m about to use it! Wish me luck!

    -Slave.

  • Afraz

    Can I use coldfusion mailer script instead php? I mean I’ve change email.cfm

    $.ajax({
    type: “POST”,
    url: “bin/email.cfm”,
    data: dataString,

    But it’s not workign. It displays Success message but no email delivers to my mail box. Moreover, I’ve checked email.cfm in a simple form, it’s functioning correctly.

    Any one can guide me plz?

  • Ryan

    Is there anyway to submit the form without using a submit button, say when a text box is updated?

  • John

    Nice approach! Here my situation is even harder: When I fill out data in a edit page and submit, I want the AJAX send the key data, say, persone ID, to server to see if the key is already in DB. If so, then server respond an error, so the AJAX will display error without leaving the edit page, just as your example here, but it is just the server validation step. If server returns success, I want to JQuery script to submit the entire form to server, and the server will render a new page, which is a different page, and my edit page should be replaced by the new page. Is it possible to do this in JQuery and AJAX?

  • Edith

    Good Script !
    Regards from Chile =)

  • http://www.colinmurphy.eu Colin Murphy

    I have created a similar tutorial on a no page refresh contact form using JQUERY, AJAX and PHP.

    http://www.colinmurphy.eu/?p=58

  • luka

    it doesnt work in chrome for me. only for me ?
    anyone else had problems with chrome ?
    chrome doesnt show error messages…

  • http://www.raindev.org John

    This is greeeat, congratulations !!!!!!!!!

  • Pingback: How to Create A Simple Web-based Chat Application « Nguyen Huan's blog

  • http://lifewitfaith.co.nr francis

    HardCoding Whew please Show us the perfect Code!!i

  • http://www.latestdiscountvouchers.co.uk nick

    Thanks, you’ve given me some really useful information which should help me debug a previously working Ajax script…

  • jahlife

    Can someone offer an additional step of how to use JQuery .Load function to first load the contact form, then process the form?

    Thanks for any feedback.

  • Pingback: 13 Most Useful Jquery Effects to Build Interesting Website | Vishnu Valentino

  • http://www.nicholasgann.com Nick

    I don’t receive the email and am not sure why. What’s with all the emails being called? and what needs to happen in order to actually recieve the mail?

  • Pingback: 10 Amazing Ajax Css Form Tutorials

  • http://www.ufu.br Jefferson

    Thanx sooo much !! Regards from BRAZILLLLL !!!

  • http://www.internet-thinkers.com Lindsay

    Thanks very much! I was looking for a good tutorial like this.

  • Pingback: 50 Useful jQuery Plugins to Enhance your Forms - Noupe Design Blog

  • Pingback: 50 Useful jQuery Plugins to Enhance your Forms « qeqnes | Designing. jQuery, Ajax, PHP, MySQL and Templates

  • Mike

    inettuts is simply one of the worst sites on the web for teaching poor quality code. Everything I’ve followed from here has later turned out to to be the wrong way to go about things.

  • samuel

    Thank you so much for the tut. Most tut’s I find are over complicated and written very poorly. This one is so refreshing.

    I do how ever have a major issue. I am not able to catch the data on the page it is sent to. I’m using php and Both $_POST and $_GET doesn’t work. I have tried to catch both dataString and the individual input names with no result.

    How do I go about getting this sent data into a PHP variable on the page it is sent to.

    Cheers

    Samuel

  • Pingback: 10 użytecznych technik jQuery

  • http://www.chanderi.net salman ansari

    thax but i want to us it with asp.ne page..how it possible with aspx page..can u help me…

    • Dazy

      Hi,

      I also want this same solution for my ASP.Net (C#) web app.

      Have you got your solution? Can you share yours?

      Regards,
      Dazy

      • Marvl

        Best thing is to get rid of ASP and use industry standard PHP/Javascript/jQuery. You will find it more robust, less prone to bugs, easier to understand, and cheaper. Microsoft sucks, as you no doubt know.

  • Vinny

    input type=file, can that be serliazed? If not, I’m assuming a plugin will have to do?

  • Mark

    I haven’t tried to see if this works for me yet, but I just have to say that the way this tutorial is written is probably the best I’ve ever seen from online tutorials.

    It’s great that you don’t make assumptions about what the readers might or might not know and just explain things thoroughly – this makes the tutorial useful for so many more people than many tutorials out there. In fact, some parts WERE obvious to me, but I don’t mind it at all, because every reader can take what they want/need from the tutorial to fill in the gaps in their knowledge.

    Thanks, and I wish all tutorials were written like this.

  • http://ursdeep.wordpress.com Deep C

    Wonderful Tutorial. You made it very simple to use and understand it. Thanks :)

  • Pingback: Fade out panel at end of onclick handler

  • Pingback: 25个 jQuery 实例教程 | 高品质 HTML+CSS 制作服务 - SonicHTML

  • Chekit

    Is it working with textarea? Can’t display message for textarea field! :(

    • Chekit

      I have found solution: just if (!text) { } :) Thanks a lot for tutorial.

      • User21

        Could you explain what you’ve done to make textarea working pleeeeeaaase?

        Thanx ;)

    • Ivan

      in js file:

      var message = $(“textarea#message”).val();
      if (message == “”) {
      $(“label#message_error”).show();
      $(“textarea#message”).focus();
      return false;
      }

      the tricky part in php:

      if ((isset($_POST['message'])) && (strlen(trim($_POST['message'])) > 0)) {
      $message = stripslashes(strip_tags($_POST['message']));
      $message=nl2br($message);
      } else {$message = ‘No message entered’;}

      you need $message=nl2br($message); (it breaks the carriage returns)

  • Sean

    I’ve managed to get this all working on my site…except for the most important bit which is getting it to send an email! Have spent the last hour reading through all the posts and have followed various tips but still no joy.

    I’ve updated phpmailer.php to the latest version (5.1) and replaced the following in process.php (as per the readme.txt):

    $to = ‘seanbetts@###.com’;
    $email = ‘seanbetts@###.com’;
    $fromaddress = “‘seanbetts@***.com”;

    $mail->From = “seanbetts@###.com”;

    STILL NO JOY!

    Can anyone help?

    Thanks

    • Jason Reichart

      Same here, can’t figure out why it wont send mail! Anyone can help with those values?

      • David Sagot angulo

        i have the same problem, i don´t know how to set de email adress where a wish to get de contacts forms

    • http://www.network-studio.co.uk Scott

      Hi Sean did you manage to resolve this issue?
      I am currently having thesame issue and dont have any joy receiving emails?

    • Jen

      I am unable to get it to email the results to me. I updated process.php file as directed and still no luck.

  • http://www.raghibsuleman.com/ Raghibsuleman

    good work….

  • http://www.mexzhouse.com max

    thanks. i am trying now.

  • iviewclear

    Same issue that Samuel has

    I am not able to catch the data on a php page.
    I’m using php and Both $_POST and $_GET doesn’t work. They are empty
    Any solution ?
    Thanks

  • Pingback: Send HTML form results in an email from PHP using jQuery AJAX | Two Step Media Blog

  • RowGM

    Instead of using this,

    # var dataString = ‘name=’+ name + ‘&email=’ + email + ‘&phone=’ + phone;

    you should use: .serialize()

  • http://www.network-studio.co.uk Scott

    I like Sean above cannot get it to send email.
    Please can someone kindly guide me in the right direction?

  • http://cefstory.com cefer

    very userful for me..
    thanks a lot..
    regards.

  • mary

    ok, it’s a good form – but what about the validation? you can type anything into the fields and the form still validates. I’m not too good with query/ajax. so does anyone have a better way of validating this form other than just “required fields”? what about a valid email address format, more than 2 characters and no integers for the name?

    I’m trying to use the Validity plugin found here:
    http://validity.thatscaptaintoyou.com/Demos/index.htm#SpecializedValidation
    but it’s just not happening. any help is greatly appreciated – possible monetary reward too?

  • http://www.nicedicedesign.com nicedice

    Hi
    Nice tut, a few holes here and there but very good for giving a general well explained overview of JQuery and Ajax.

    One question … does any one know how to put a back or refresh button on the 2nd stage to reload the form back in?

    Also – a lot of people are having problems with the php in the process.php file, if you don’t understand it then find another php mailer script and replace the whole content of process.php with it. Some minor modification will be need to suit your needs but it would be easier than trying to understand phpmailer.php.
    Many can be found with a simple google search, good luck!

    Any input for the refresh or back button is appreciated.
    Cheers all.

  • Jasher

    Thanks a lot for this script.

    I have applied it here : http://layersdesignstudio.com/websites/ml/index-form-trial.html

    (Click on the “contact” symbol, its in a slider)

    What do I modify in process.php to get this form to be sent by email?

    thanks

  • Pingback: 50 jQuery Form Plugins, Tutorials and Resources | webdesign14.com

  • kai

    Hi!

    How did you get the the TEXTAREA to work when displayed? I tryed hard the “solutions” explained in the other comments. none worked.

    Here my string:

    var news = $(“textarea#news”).val();
    if (comment == “”) {
    $(“label#news_error”).show();
    $(“textarea#news”).focus();
    return false;
    }

    It always displays the “no news written” message in the email returned.

    Thanks in advance for help.

  • neoweiter

    Does anyone know how to use validation for checkboxes?

    I have another working php script for email sending, but it doesn’t work when the ajax validation script is activated… Does someone know how to make the ajax and PHP scripts work together?
    (I already tried to place it in the url: ‘ ‘, field in the ajax script, and in action=” ” in the HTML code…. none works)

    thx ;)

  • http://webwarecollection.com Wilson

    I am concerned about the additional class-text-input attribute in the html form’s input boxes, I cannot find any references to it in the code. Is it safe to remove it?

  • Pingback: 30 Fresh AJAX Tutorials And Techniques | Emre Saraçoğlu's Official Blog

  • Pingback: Enviar formularios sin recargar la página | Entra-ya

  • Sandip Rajput

    It was great helpful to understand how to send form data without refreshing web page, also it is simple script flow by using jquery.

    I am using one common form and submit four different fields data for processing by using jquery ajax, for this i use each fields has button to click on that button the filed value is send and processing get back to the page showing the resulted data on that page. After fill all fields to submit this whole form data. my problem is- Can I use this script for that? if not. Please anybody help me….

  • Jason

    Sorry, this tutorial gets an F because the author doesn’t walk through the most important part, the process.php file. To echo a previous commenter’s question, why are there so many variables in the process.php file? I can count seven separate variables for email address? What the heck? No explanation, no fix to the article after 8 pages of comments. Sorry guys, great attempt, but why not back it up with some answers?!

    $to = ‘someone@example.com’;
    $email = ‘email@example.com’;
    $fromaddress = “you@example.com”;
    $fromname = “Online Contact”;

    ????

    • Bruce

      Jason,

      did you solve your problem? If you using .ajax and jquery to send post data to php is come into the script using $_REQUEST not $_POST or $_GET

  • http://www.askinterview.com sumir

    is that any buddy tell me how to set focus in a loop on different id’s help me……….

  • halau

    Sending to email address does’nt work!

    Does anyone can help guys who have this problem?
    Thank’s