Submit A Form Without Page Refresh using jQuery

Jul 24th 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.

PG

Author: Eric

Eric is a freelancing web designer/developer (Renkai Designs at www.renkai.com), amateur blogger at Digital Design Diary, SEO specialist, rock guitarist (band coming soon!), mountain biking enthusiast, and avid coffee drinker.

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.

 


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Andrei Constantin July 24th

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

    ( Reply )
  2. PG

    sanjay July 24th

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

    ( Reply )
  3. PG

    The Frosty July 24th

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

    ( Reply )
  4. PG

    aNieto2k July 24th

    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.

    ( Reply )
    1. PG

      Spider June 9th

      u mean we dont have to write the dataString as well?? if we wont write it how would we use this dataString ?

      ( Reply )
      1. PG

        Hans van Domselaar July 3rd

        var dataString = $(”#contact_form form”).serialize()

        All fields with a name property are affected by the serialize function.

        Isn’t that easy?

  5. PG

    insic July 24th

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

    ( Reply )
    1. PG

      nick March 10th

      good yeu fill beautiful girl

      ( Reply )
    2. PG

      sundar March 13th

      fine doing well

      ( Reply )
    3. PG

      sexi boy March 27th

      kiss…

      ( Reply )
      1. PG

        ezra April 7th

        love u

    4. PG

      hair May 22nd

      such a beautiful lady…

      ( Reply )
      1. PG

        Singh May 25th

        wow guys get off the pc for 5 mins lol

        nice tutorial, will be using this !.. like right now haha

      2. PG

        nick August 30th

        nice girl..i love u

  6. PG

    KAZI July 24th

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

    ( Reply )
  7. PG

    Neil Berrow July 25th

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

    ( Reply )
  8. PG

    Imzyos July 25th

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

    VS

    $(”form”).serialize();

    ( Reply )
    1. PG

      Thomas March 31st

      Thanks – this is what I was after – why rewrite this code for each form?

      ( Reply )
  9. PG

    Peter July 25th

    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.

    ( Reply )
    1. PG

      Snapper April 19th

      I have to agree here. As I am learning AJAX and jQuery I found this tut along with others and gave a go at a combo of practical uses. The submit button as well as the fields should be disabled as the form is being sent to the server.

      Where I disagree is with the second issue. I agree that a lot of people are browsing the internet with browsers other than those installed on a computer, but a lot of those micro browsers are also javascript enabled. However, some don’t and for that reason designers should be making, at the least, their most important features available in a mobile browser environment.

      ( Reply )
  10. PG

    Mark Bowen July 25th

    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

    ( Reply )
    1. PG

      moron finder July 31st

      what a moron you are… there’s always one of you floating around.. if somebody doesn’t have javascript enabled then what are they doing on the internet??? It’s really that simple.. next you’ll be saying… what if people don’t have flash installed how can they view youtube videos or use bbci player? easy.. they don’t get to!!!

      ( Reply )
      1. PG

        chmee August 20th

        AND : there are user without js and flash! do you know lynx?

        Anytime there are some “moronfinder” outing themselves as lord-of-the-morons.

        BUT : for a simple ajax-tutorial you should show the response-handling as well.

  11. PG

    Ben Griffiths July 25th

    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.

    ( Reply )
  12. PG

    Guillaume July 25th

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

    ( Reply )
  13. PG

    Niall July 25th

    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!

    ( Reply )
  14. PG

    James July 25th

    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

    ( Reply )
  15. PG

    davidinbcn July 25th

    disable the submit button when u submit…

    ( Reply )
  16. PG

    roger   July 25th

    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!

    ( Reply )
  17. PG

    David July 25th

    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

    ( Reply )
  18. PG

    Shane July 25th

    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.

    ( Reply )
    1. PG

      Chris September 7th

      how would you go about doing that?

      ( Reply )
  19. PG

    Daniel July 25th

    nice tutorial, very useful! thanks a lot.

    ( Reply )
  20. PG

    Alex July 25th

    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!

    ( Reply )
  21. PG

    Jake G. July 25th

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

    Thanks!

    ( Reply )
  22. PG

    Rijalul Fikri July 25th

    This what I looking for, thx’s

    ( Reply )
  23. PG

    Michael Thompson July 25th

    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.

    ( Reply )
  24. PG

    Andrejs July 25th

    It is very useful script.

    Thanks a lot.

    ( Reply )
  25. PG

    Nate July 25th

    This will come in very handy. Thanks

    ( Reply )
  26. PG

    Mike Busch July 25th

    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.

    ( Reply )
  27. PG

    Ben Griffiths July 25th

    @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?

    ( Reply )
  28. PG

    kiran voleti July 25th

    This is good one.

    Thanks
    http://www.toputop.com

    ( Reply )
  29. PG

    dlv July 25th

    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!

    ( Reply )
  30. PG

    Snorri3D July 25th

    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

    ( Reply )
  31. PG

    Steve July 25th

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

    ( Reply )
  32. PG

    Barndizzle July 25th

    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.

    ( Reply )
  33. PG

    raj dash July 25th

    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 :)

    ( Reply )
  34. PG

    Dan July 25th

    Useful

    ( Reply )
  35. PG

    Al July 25th

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

    ( Reply )
  36. PG

    Dave McFarland July 25th

    @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.

    ( Reply )
  37. PG

    Taylor Satula July 25th

    Very cool, looks good too!

    ( Reply )
  38. PG

    crysfel July 25th

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

    ( Reply )
  39. PG

    Monkeytail July 25th

    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

    ( Reply )
    1. PG

      Craig May 7th

      html() sets the entire contents of the selected element.
      append() adds the content to the end of what is already in the selected element.

      So basically .html(”Contact Form Submitted!”) replaces the form with the text ”Contact Form Submitted!”, and .append(”We will be in touch soon.”) adds extra text to the end of the text that has just been placed in the form.

      To achieve the same result using 2 html’s or 2 append’s, you would need to either do something like:
      $(this).html(’First bit of text’).html($(this).html() + ‘Second bit of text’);
      or:
      $(this).empty().append(’First bit of text’).append(’Second bit of text’);

      ( Reply )
  40. PG

    Mr. Haynes July 25th

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

    ( Reply )
  41. PG

    Braden Keith July 25th

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

    ( Reply )
  42. PG

    Andrew July 25th

    Another nice tut! Gotta love that AJAX!

    ( Reply )
  43. PG

    Braden Keith July 25th

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

    ( Reply )
  44. PG

    James July 25th

    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.

    ( Reply )
  45. PG

    Philsbury July 26th

    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

    ( Reply )
  46. PG

    Josh Riddle July 26th

    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/

    ( Reply )
  47. PG

    Matrich July 26th

    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.

    ( Reply )
  48. PG

    Trevor Davis July 26th

    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.

    ( Reply )
  49. PG

    Joefrey Mahusay July 26th

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

    ( Reply )
  50. PG

    Mark Abucayon July 26th

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

    ( Reply )
  51. PG

    Eric July 28th

    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.

    ( Reply )
  52. PG

    Dwayne July 28th

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

    ( Reply )
  53. PG

    joelrthomas July 29th

    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!

    ( Reply )
  54. PG

    Fox July 30th

    Awesome. It’s very useful.

    ( Reply )
  55. PG

    jesusvld July 31st

    Excellent! nice work!

    ( Reply )
  56. PG

    Ashok.p August 4th

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

    ( Reply )
  57. PG

    Maicon August 5th

    Great work! I learned a lot!

    ( Reply )
  58. PG

    ebot August 5th

    nice tuts!!!

    ( Reply )
  59. PG

    Janpeter August 5th

    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…

    ( Reply )
  60. PG

    mattems August 11th

    awesome.

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

    great work!

    ( Reply )
  61. PG

    TravelScoot August 13th

    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.

    ( Reply )
  62. PG

    allmoney.ws August 14th

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

    ( Reply )
  63. PG

    ralph August 19th

    very informative

    ( Reply )
  64. PG

    md5 August 21st

    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.

    ( Reply )
  65. PG

    Alberto August 23rd

    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.

    ( Reply )
  66. PG

    Coder September 1st

    1. Does not check for valid email address

    2. Phone field allows you to Input a number

    ( Reply )
  67. PG

    Ben September 4th

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

    ( Reply )
  68. PG

    Ciel September 5th

    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 :)

    ( Reply )
  69. PG

    justin September 9th

    Just curious what I’d have to do if I wanted to use a textarea box in addition to input boxes, how do i get the textarea var that i need to post to my php/process?

    ( Reply )
  70. PG

    Patricio September 10th

    Hi, I’ve read this article, and i’ve found it really interesting.
    But I came here with another problem. Probably solved with this technique:

    I want people to post comments in my website without refreshing (no new thing here)… but the comment should appear in the screen without refreshing. Could you show me how to do that? You’ve got my email anyways here it is for anyone who has the answer (patto17@hotmail.com).

    Actually what I intend to do is a similar effect that Facebook has when you comment on a photo.
    (anyone knows Facebook? guess you do)

    thanks! bye

    ( Reply )
  71. PG

    joe legend September 15th

    wowowowowowoowowowow!!
    thats a great tutorial bro, it’s kinda kool, but don’t you think that
    more things on Javascript should be touched, incase those new
    to javascript can as well uderstand the logistics.

    More grease to ur elbow

    ( Reply )
  72. PG

    Wayne September 15th

    Great stuff, used the idea with ajaxForm. Works well and with a bit of tinkering you can have an accessible form that works well with jquery validation and without javascript turned on.

    ( Reply )
  73. PG

    diand September 16th

    thanks

    ( Reply )
  74. PG

    Chaitoom September 19th

    very good :D

    So thx ……

    ( Reply )
  75. PG

    ordersomabuyg September 21st

    Wow Cool !
    Super Man
    Nice Site

    ( Reply )
  76. PG

    scriptsrule September 29th

    worth reading

    ( Reply )
  77. PG

    satish October 7th

    very good …. kepp rocking

    ( Reply )
  78. PG

    justin October 11th

    any idea how i can grab an upload file from process.php with this?

    ( Reply )
  79. PG

    Carlos @ VPSmedia October 24th

    Great stuff, will give it a try now.

    ( Reply )
  80. PG

    Carlos October 24th

    very good the information, thanks!!! gracias!!!

    ( Reply )
  81. PG

    kuldip October 29th

    Very Nice! is there any way to do this without the php? if u already have a CGI post script?

    ( Reply )
  82. PG

    bob October 31st

    Awesome

    ( Reply )
  83. PG

    Jatin Meshiya November 5th

    Thanks a lot. We get exact what we want!! We are looking forword to have some more tutorials like this from you. Thanks again.

    ( Reply )
  84. PG

    Rajasekaran November 8th

    Hi. Really this site contain very source and explanation.

    Thanks lot.

    Rajasekaran
    http://www.adityams.com

    ( Reply )
  85. PG

    zed November 12th

    Can someone please elaborate on how to make this more appropriate for a live site (since that is why we are probably trying to make forms). The author mentions putting the php into the contact form itself. Can someone please help me understand how to do this? I very much like how this form works but I do not want to lose functionality if the browser does not have javascript.

    ( Reply )
  86. PG

    samurai November 13th

    Thanx nice tutorial

    ( Reply )
  87. PG

    csource November 16th

    Great tutorial!
    Very clear and useful. Thanks a lot.

    ( Reply )
  88. PG

    theman November 21st

    but let’s say i want to submit some data but then want data returned from mySQL. how would i do that?

    ( Reply )
  89. PG

    suresh November 21st

    Great work…. :-)

    ( Reply )
  90. PG

    whatever November 24th

    LOL to all ppl that are saying “great job”

    ( Reply )
  91. PG

    Kevin November 26th

    Very good tutorial. Exactly what i was looking for.

    ( Reply )
  92. PG

    Tim November 29th

    Thanx Guys!!

    ( Reply )
  93. PG

    smartpill November 29th

    I’d like to see how actual field validation (like checking for valid email) would be integrated. As mentioned above, as long as the input is not empty it will submit, so actual field validation in the example would be really helpful.

    ( Reply )
  94. PG

    shinoj k December 2nd

    how i can i store dis values database table.I hav done program for saving it.But it’s not working and it will showing the messege.Wht is the reason
    any body know plz hlp me.thanks in advance.

    ( Reply )
  95. PG

    HITSROSE December 5th

    Vary nice …

    ( Reply )
  96. PG

    jt December 7th

    great article but i’m having a HECK of a time figuring out how to scale this method out to other form fields though. (like drop-downs, check boxes, radio buttons and additional text) fields.

    what files and in exactly what way do i need to update in order to add additional fields?

    i can add additional text fields OK but can’t figure out how to get the error messages to show under the new text fields. and i can’t seem to figure out how to add drop-downs, radio buttons, etc so that they return the results in the email at all.

    any and all help is MUCHO appreciated man!!!

    thanks,
    j

    ( Reply )
  97. PG

    TJ December 9th

    This is a great tutorial…thank you so much! Very informative.

    ( Reply )
  98. PG

    matei December 12th

    everything is superbe, except where can I put my mail, so I get the form message

    ( Reply )
  99. PG

    Fred December 13th

    How would this work with an additional “textarea” field. It doesn’t seem to work with the current code?

    ( Reply )
  100. PG

    santosh December 16th

    really really good …searching for such example from long time…
    want to say thanks from heart…….

    ( Reply )
  101. PG

    Maria December 18th

    I´m a newbie.
    Where do I input the emailadres which will stand as a reciever for the form?!!

    Help….

    ( Reply )
  102. PG

    Yasir Haleem December 22nd

    very nice tutorial

    1 question ?
    how event will work on newly appended html, i just started jquery, when i append new html with same css selector event not work can you please help me regarding this problem.

    ( Reply )
  103. PG

    Kai December 31st

    I’m not sure why sending the mail isn’t working. The form seems to operate fine.

    My settings:

    $to = ‘info@br**k.com’;
    $email = ‘info@br**k.com’;
    $fromaddress = “info@br**k.com”;
    $fromname = “online contact”;

    What’s the $email for anyway? What about all the other from, to, etc variables below these lines? That is not clear from your readme file… could you please help me out? Cheers

    ( Reply )
  104. PG

    Rishabh sahu January 2nd

    very nice things ,very useful in web applications

    ( Reply )
  105. PG

    Loga January 7th

    Hi.. I want to submit values from a form to the database and once again retrieve values from the database and display it in the same page using AJAX and Jquery. Could anybody kindly suggest some ideas please.

    ( Reply )
  106. PG

    Rob January 8th

    Hi. Great tutorial. I am also having problems adding extra fields, such as drop-downs and textarea. How do I get these to work?

    Many Thanks!

    Rob.

    ( Reply )
  107. PG

    Rob January 8th

    To get values for different input types you can use the following in tutorial.js

    Example of drop-down list ‘worktype’:
    var worktype = document.getElementById(’worktype’).value;

    Example of textarea ‘query’
    var query = document.getElementById(’query’).value;

    As long as you give your form element an ID these will get the values for you.

    Rob.

    ( Reply )
  108. PG

    Manu January 8th

    Kai, I have the same probleme, anyone to help us please ?

    ( Reply )
  109. PG

    Brad Frost January 8th

    I am also having the same issue as Kai and Manu. I simply uploaded the tutorial files to my server, changed the minimum variables:

    $to
    $email
    $fromaddress
    $fromname

    to my email address instead of the example addresses, and the form does not send an email. The Jquery bit works just fine, there must be something wrong with the PHP.

    ( Reply )
  110. PG

    Staffan Estberg January 12th

    Great method! I’m having trouble however getting non-standard characters to display correctly in my e-mail outputs – in particular the Swedish characters “ĂĄ”, “ä” and “ö”. I’m guessing this is because the php document requested through ajax doesn’t know what document encoding is chosen, and it defaults to something else than utf-8. I’ve tried to declare this in the php but to no success. Any ideas?

    ( Reply )
  111. PG

    Monsieur fion January 14th

    Hi,
    Rob please, can you say me where I must insert “var query = document.getElementById(’query’).value;” ?

    I try but, that bug :(

    ( Reply )
  112. PG

    daTO January 14th

    Fantastic !!

    ( Reply )
  113. PG

    Monsieur fion January 14th

    PLease, help me with this problem : where I must insert “var query = document.getElementById(’query’).value;” ?

    Thanks !!

    ( Reply )
  114. PG

    ahmad farid January 16th

    Finally, i came a cross to this tutorial. this is what i’ve been looking for. will try it . Thanks a lot.

    ( Reply )
  115. PG

    Deep Shrestha January 22nd

    great work i like it…

    ( Reply )
  116. PG

    Steve January 26th

    Same issue as a few other people so far. Changed the values in process.php but am not receiving any kind of emails.

    Any thoughts?

    Thanks.

    ( Reply )
  117. PG

    mohammed January 30th

    pretty good

    ( Reply )
  118. PG

    Alex Dichev February 3rd

    Useful. Thanks!
    It works fine with only a few small cosmetic modifications.

    Good luck!

    ( Reply )
  119. PG

    Merrick Christensen February 3rd

    This is a cool and raw way to do it. But why reinvent the wheel when the Form plugin is so effective?

    ( Reply )
  120. PG

    Tom February 4th

    I like that one. fairly easy, i will give it try.
    Thx for your tut!

    ( Reply )
  121. PG

    Cristian February 6th

    This is cool, i’ll use it

    ( Reply )
  122. PG

    Dayton Nolan February 7th

    This is a terrible tutorial. The whole architecture is flawed. Without JS enabled there will be two labels per input, one of them being an error message. Not to mention it won’t even work. This is goes against everything that the jQuery framework is about. I would recommend that people not follow this tutorial and read jQuery’s documentation. It’s just as easy to read and promotes proper use.

    ( Reply )
    1. PG

      Doug April 10th

      Can you suggest an alternative?? there seem many different concerns with it. I think everyone agrees its awesome in theory, but struggling with the application.

      The problem I’m having is with the process.php, I got no idea how to do the email address and the readme.txt is pretty vague (and I’m a complete a newb)

      Great tute tho would be a lot more satisfying if i got it working. perhaps someone, who knows what they’re doing, reading and replying to these comments would help

      ( Reply )
  123. PG

    Rollins February 7th

    Wow! To think I’ve been scouring the web searching for this. Thanks man. I’ve been trying to create an ajax contact form which works within a lightbox Modal box, and it’s really been “hell” (forgive the expression).

    Anyway, I think I’ll check this out and see what comes out it.

    Thanks again.

    ( Reply )
  124. PG

    Rollins February 7th

    I must say I share your concerns Dayton. Just finished running a couple of tests myself. The search continues then ……

    ( Reply )
  125. PG

    wignyo February 7th

    nice post gan

    ( Reply )
  126. PG

    sixteen11arts February 9th

    wow cool

    ( Reply )
  127. PG

    Lewis Litanzios February 9th

    Certainly educational, but unfortunately I’m not going to use this form because it lacks JS degradation.

    Perhaps a post revision in the future, including some basic PHP functionality to get the job done. That would be good of you Eric :]

    Cheers mate. Learned a lot here regardless.

    ( Reply )
    1. PG

      Kqzfyetm April 30th

      http://forums.developerone.com/member.php?u=42001 [url=http://phoronix.com/forums/member.php?u=19400]cheap propecia[/url] generic cialis ynxd

      ( Reply )
  128. PG

    Lewis Litanzios February 11th

    Doesn’t work.

    ( Reply )
  129. PG

    Storm February 13th

    Thanks, great tutorial

    ( Reply )
  130. PG

    Ludo42 February 13th

    Thanks, this is cool !

    ( Reply )
  131. PG

    Kevin February 20th

    After submitting the form, I’m expecting process.php to print out the following, but it doesn’t. It’s in php, but it doesn’t appear…any ideas?

    Name

    Email

    Phone

    ( Reply )
  132. PG

    lawrence77 February 21st

    i like the final even though i dont know what is jQuery!

    good work!

    ( Reply )
  133. PG

    s1 February 24th

    hi……

    ( Reply )
  134. PG

    suman February 24th

    heloooooo

    ( Reply )
  135. PG

    brian February 25th

    Dont waste your time its impossible to get working on a server spent 1 day on it managed to get the half working needs reprogramming for extra fields like textarea got all that done and php fields etc, couldent get the php part to work, unless you are a computer programmer i would stay well clear, very nice effect, it works locally on my computer the ajax/java effect part, its a pity the comments left were not more to do with the technical detail of installing on a server, bye the way has anyone got this to work??????

    ( Reply )
  136. PG

    brian February 25th

    ps: I read something about the POST Method that as the .php of this email form is static and the ajax/java are the latter that you could use abyss software to handle the post back issue, i was getting 405 Error! when i inserted action “process.php” in the form,i got the form tutorial.html but no fade in action or message after i press the submit button just a static pic of the table with out the css effects etc, this was working from my hosting server that supports php. i dont know i have given up

    ( Reply )
  137. PG

    Gareth Watson March 1st

    I was able to get this working on my local machine but no on our live server. For now there are too many issues with this script to use in a live environment. But that’s OK, this is a tutorial and it’s intended to help me learn JQuery better. For now my skills are too limited to make the necessary changes to this form that I require. Perhaps in time I can return to this and make the relevant changes but for now i have pass I’m afraid. Shame really, it was a funky little piece of code!

    ( Reply )
  138. PG

    Diego Brito March 3rd

    Guys to use a textarea box I have a simple trick.

    Only change this “$(”input#mensagem”).val();” for this “$(”textarea#mensagem”).val();” in tutorial.js file.

    Good Script Thankyou Eric!

    ( Reply )
  139. PG

    Robbie March 4th

    Diego Brito:

    Was to ask about it! heheheh
    lucky me…thanks and thanks 4 google too

    ( Reply )
  140. PG

    Robert March 5th

    Well, well, what if i use text editor like TinyMCE ? is it the same ?

    ( Reply )
  141. PG

    nathan March 6th

    1) where exactly do you put the email address the form is being sent to?
    2) how can i make it check to see if the email entered is valid, the form doesn’t even check for the “@” sign

    ( Reply )
  142. For those of you unable to get the submit to actually send an email, the version of phpmailer included with this download is out of date.

    http://phpmailer.codeworxtech.com/

    Get a new one and never pull out another hair. It’s very simple from here. Good luck.

    ( Reply )
  143. PG

    advise-art March 12th

    Very nice tutorial. I’ll test it in my next website …

    ( Reply )
  144. PG

    Sam Crockett March 12th

    Good write up. And more importantly thanks to all those that left relevant comments containing ways to correct/expand the functionality of this example.

    ( Reply )
  145. PG

    naspinski March 16th

    I noticed that you process only the success in the the jQuery ajax() method. One thing that I realized, is that even if the page I post to is set to error out, it will return success… any idea on how to test for errors?

    Right now I am passing back a string, that will tell me if it is error/success, but it is still not caught with the jQuery (it looks like a success). But I would like to know how jQuery handles it.

    ( Reply )
  146. PG

    kumar March 20th

    is it possible to send very very big amount of data , that is url is having some limitation to send data. if i want to send the data more lengthier than the capacity of url.

    for example big newsletter

    ( Reply )
  147. Think we will use this on our web site also!

    ( Reply )
  148. PG

    Joe March 31st

    Nice! Might want to go into more details about the process.php file for some of us noobs.

    ( Reply )
  149. PG

    Took March 31st

    Very good article. Thank you very much.

    ( Reply )
  150. PG

    sangam uprety March 31st

    Really awsome article. I have resolved to use this in my coming project. Thanks a lot!

    ( Reply )
  151. PG

    Ashish Wadatkar April 5th

    its very helpful for me,thanks a lot…………

    ( Reply )
  152. PG

    praveen April 6th

    very nice tutorial

    ( Reply )
  153. PG

    Mike April 10th

    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. So if you know of a way to accomplish that without using runonload I would be happy to hear from you about that.

    After:
    $( “.error” ).hide();

    just put:
    $( “input#name” ).focus();

    and then the rest of the code:
    $( “.button#submit_btn” ).click( function()
    {……

    ( Reply )
  154. PG

    Keyur Shah April 22nd

    Hi,
    This is an awesome form submit.
    I must say I am a newbee to jquery. But would like to know something probably which might be relevant to such form submission,

    I am using simple image verification prior to form submission. Through the JavaScript code I check all the relevant fields and if the user has entered a wrong verification number (which is in session) how would I show him the error?

    Meaning:
    $.ajax({
    type: “POST”,
    url: “bin/process.php”,
    data: dataString,

    // NEED TO SHOW ERROR IF THE VERIFICATION NUMBER, WHICH IS IN SESSION, DOES NOT MATCH.

    // IF THE VERIFICATION NUMBER MATCHES THEN CONTINUE…

    success: function() {
    $(’#contact_form’).html(”");
    $(’#message’).html(”Contact Form Submitted!”)
    .append(”We will be in touch soon.”)
    .hide()
    .fadeIn(1500, function() {
    $(’#message’).append(”");
    });
    }
    });

    Any help will be much appreciated

    Thanks
    Keyur

    ( Reply )
  155. PG

    Phillipinnes April 22nd

    whats a shit ?

    ( Reply )
  156. PG

    Phillipinnes April 22nd

    I mean cool tutorial man ))) thank you ))) I did a worst way of email validation but it works )))

    in tutorial.js

    find
    if (email == “”)

    replace with
    if (email == “” || email==null || email.length==0 || email.indexOf(”@”) < 1 || email.lastIndexOf(”.”) =0 || email.indexOf(”.”) == email.length)

    ( Reply )
  157. PG

    Butch Decossas April 27th

    It works!

    perfect.

    Thanks a lot

    ( Reply )
  158. PG

    Miguel April 28th

    i need help i can’t get the process.php form to work correctly!

    ( Reply )
  159. PG

    Chris April 30th

    Great work! Took about 4 minutes to get it working. Can’t speak for the php because I used my own script, but the JS is great and looks fantastic.

    ( Reply )
  160. PG

    Aaron April 30th

    hmmm.test

    ( Reply )
  161. PG

    Mahak May 1st

    good stuffs..:)

    ( Reply )
  162. PG

    Raghu May 4th

    Good tutorial to explain a person who is new to JQuery and how it works.
    The main advantage is it is integrated with the usage of the ajax function.

    This particular tutorial makes lot more sense to most of the .Net dev’s.

    Thanks.

    ( Reply )
  163. PG

    dan May 5th

    really like it !

    is there away of adding a captcha script to this ??

    ( Reply )
  164. PG

    Richard May 5th

    Hi everyone… Big thanks for the tute, it is fantastic.

    As I am new to a lot of these more in depth scripting process (ie: AJAX, jQuery etc) I was hoping someone could assist just a little.

    I am simply trying to work out what I need to remove to have some input fields not require a response. I can get all my fields working but they all require a response, any change I make seems to break it.

    Any help would be fantastic.

    ( Reply )
  165. i love it- very nice.

    but i have a question: the script dont show the email like:

    Email No email entered

    whats wrong?

    ( Reply )
  166. PG

    eques May 15th

    normaly i dont post a message, but this article gave me a very good insite in the overal principles of jquery, it suddenly all became a lot more clear to me. Thanks a lot

    PS is there a way to make an account so that you can login and such ? (not the paying option)

    ( Reply )
  167. PG

    Ahmed May 18th

    It is very useful script for me as a beginner in jquery,
    BUT ,
    how can we add loading icon while the script processing the code?

    ( Reply )
    1. PG

      Levani May 24th

      Good question! Can anyone answer, please?

      ( Reply )
  168. PG

    yuyin May 26th

    data: $(this).serialize(),

    ( Reply )
  169. PG

    Victor Bejar May 27th

    Nice tutorial!!! It was exactly what I was looking for my project.
    Regarding the process.php, I made it work on PHP5 in this way (I hope you find this helpful):

    Download the last version of PHPMailer (version 5.0.0):
    http://phpmailer.codeworxtech.com/index.php?pg=phpmailer

    Uncompress and copy the class.phpmailer.php file to the bin folder.

    Replace the code from process.php with (modify the variables indicated according your needs):

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

    Name

    Email

    message

    SetFrom($from, $fromname);
    $mail->AddReplyTo($replyto, $replyname);
    $mail->AddAddress($to, $toname);

    $mail->IsHTML(true);

    $mail->Subject = $subject;
    $mail->MsgHTML($body);

    if(!$mail->Send()) {
    $recipient = ‘your_email@example.com’;
    $subject = ‘Contact form failed’;
    $content = $body;
    mail($recipient, $subject, $content, “From: mail@yourdomain.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail”);
    exit;
    }
    ?>

    ( Reply )
  170. PG

    Levi May 27th

    Great tutorial.

    But i am left with the problem of no email validation:

    the present script:

    var email = $(”input#email”).val();

    if (email == “”){
    $(”label#email_error”).show();
    $(”input#email”).focus();
    return false;
    }

    Only forces the uses to put it a character, and When i treid to get a real email validation function and integrate it i was unsuccessful .

    If anyone has and ideas to solve this please share.

    Thanks

    ( Reply )
  171. PG

    Paula June 2nd

    Great tutorial! Exactly what I was looking for! I’m gonna use it for my website.
    Congratulations!

    ( Reply )
  172. PG

    wpdigger June 3rd

    the demo looks very good. Thx and cheers,

    ( Reply )
  173. PG

    Taki June 4th

    Very easy to follow tutorial! Thank you!

    Q: I need my form to show the data in an array because I have several groups of checkboxes: data[1], data[2], data[3], moredata[1], moredata[2], moredata[3].

    Will this work with array data? I tried but couldn’t get it. Am I doing something wrong or is it not possible?

    ( Reply )
    1. PG

      Taki June 4th

      Got it working with arrays! Thanks. I want to say again, this tutorial was so easy and clear I hardly had to think at all! :-) There are other tutorials with more info, but they require much more effort to understand.

      ( Reply )
  174. PG

    Kathy June 5th

    Great tutorial….but I’m having trouble using the form on a WordPress page and MOST IMPORTANTLY sending the form data to my
    MySQL table instead to as an email in the process.php

    Can get process.php to run at all.!

    ( Reply )
  175. PG

    Gaurav M June 6th

    Love it

    ( Reply )
  176. PG

    Zach June 6th

    I just can’t seem to get the mail portion of this to work. I’ve tried downloading an updated phpmailer. I’ve tried verifying everything in the code. Does anyone have any idea how to make this functional?

    ( Reply )
  177. PG

    rob ganly June 12th

    hi eric et al.

    nice example. i’ve got it working but need to be able to send a failure message back from process.php, for example when a db update fails. i can’t see how to do it, no matter what happens in this file it seems to equate to success… even just exiting at the top of the file! seems that success is triggered simply by the file existing, regardless of content!

    lastly, do your error messages, table etc. in process.php ever get used? i can’t see where they do.

    any help re. sending a failure back from process.php much appreciated.

    best,

    rob ganly

    ( Reply )
  178. PG

    rob ganly June 12th

    ah, i worked out what was needed… nothing was getting passed back to the success function from the php file so i added the msg param and then did a conditional on that to solve my prob. in the php file if all is fine i set it to ok, otherwise set an error msg.

    here’s the construct in case it helps anyone else:

    success: function(msg) {
    if(msg == ‘OK’)
    {
    // set success html
    }
    else
    {
    // set unsuccessful html
    }
    }

    cheers,

    rob ganly

    ( Reply )
  179. PG

    praful June 12th

    great tutorial… just what I needed

    ( Reply )
  180. PG

    Iglesio June 15th

    I take it everybody saying “this is exactly what I needed” either just received some oral, or they got this form working perfectly?

    Those of you who want billions of people visiting your site, then please re-do this form with all glitches in tact and with an easy to follow demonstration and/or downloadable files, addressing the following:

    a) Make it work without javascript turned on
    b) Ensure that the mail actually gets sent
    c) Make it easy to add additional form elements (select boxes, textareas etc)
    d) Follow up on people’s suggestions / comments

    Then my friend, internet stardom will be yours.

    ( Reply )
  181. PG

    me June 16th

    this tutorial LOOKS ood, but your php process file does not work at all. kinda mickey mouse if you ask me

    ( Reply )
  182. PG

    Alex June 21st

    Fantastic !!

    ( Reply )
  183. PG

    Khaled Musaied June 30th

    It was helpful

    ( Reply )
  184. PG

    digger July 2nd

    This tutorial truly rocks.
    One thing Ive found with jQuery tutorials is that the writer tends to assume we dont need his help, and opts to show off how much they know instead.

    Not here!

    I am a relative n00b 2 jQ (although many years in php) I found your tutorial easy to follow and simple to implement.

    Thank you, for not being a jQuery snob and providing something of genuine use to users, rather than filling your page with keywords or self appreciation.

    ( Reply )
    1. PG

      digger July 2nd

      Just read back some of the comments above mine, and felt I need to post again.

      Any PHP code posted in comments or within this tutorial can only ever be described as “An Example”. This is a jQuery tutorial, what do you expect?

      Use Google, find a php email/contact/whatever form script that works for you, alter the jQuery post action to suit, alter the output of your php script to return true; rather than any text or redirection.

      Got this working great with this: http://www.stadtaus.com/en/php_scripts/tell_a_friend_script/
      took some messing around, but was fun enough and works great.

      ( Reply )
  185. PG

    Uran July 8th

    This looks great.. but how do I make use of it if my form sits on a .php and is loaded using jQuery (function loadContent())… basically how do I call the $(function()) from a the form that sits elsewhere?

    ( Reply )
  186. Very nice tutorial and the code.

    Thanks!

    ( Reply )
  187. PG

    Adam July 11th

    I’ve been using XHR for a while, but since I’m trying to rebuild my site incorporating Jquery I thought it would be best not to re-create the wheel. After searching for a solid example with explanation for a while I came across the clear, well written, thorough example. Excellent job, thanks a whole lot for this submission.

    ( Reply )
  188. PG

    Pavel July 24th

    I was searching for similar tutorial pretty long and then I got here and found yours. It’s totally great tut and I would like to thank you for it.

    ( Reply )
  189. PG

    sheshadev July 30th

    Thank you so much , who ever written the article. It helped me so much

    ( Reply )
  190. PG

    kapil August 1st

    thank u so much .
    what a wonderful thing is this!!!!!

    ( Reply )
  191. PG

    Jonathan August 3rd

    asdasdasd

    ( Reply )
  192. PG

    rob August 7th

    I am having a problem with the form on the homepage. If I have the bin folder in my contact page and use the form there I receive the info.. but I want this form on all of my pages including the homepage. I tried having all of the files ( php and js etc) in the root but it still doesnt work.. it goes through and says the form was submitted but I never get the info – any ideas?

    ( Reply )
  193. PG

    Peter K August 11th

    I was never that good with jQuery functions, but this should get me motivated. Will give it a try tonight.

    ( Reply )
  194. PG

    James Chapman August 15th

    Just have to say this is really good, thanks…

    When testing in internet explorer (8), I get the activeX control bar come up when the page loads… any ideas how to stop this happening?

    ( Reply )
  195. PG

    Dru August 16th

    Well, looks great but for us newbies who have never used php to send the form its not much help. I’m pulling my hair out trying to work it out, tried different things but I just have no idea what I’m doing.

    I’m seeing all these comments asking how its done, but nobody taking the actual time to help them. Cheers

    ( Reply )
  196. PG

    fuedeerce August 18th

    I mow down into the payday allowance ambush, which I struggled my parenthetically a via away from of. Now when I spy someone succeeding into one of those places, I just pine for to run take over them and tear them in the inconsistent instruction! I hate plundering lenders.

    ( Reply )
    1. PG

      Tarek October 28th

      lol…try a different translator

      ( Reply )
  197. PG

    sai reddy August 19th

    Well done dude

    Nettuts rocks

    ( Reply )
  198. PG

    Blog astuces web August 25th

    very nice script :-)

    ( Reply )
  199. PG

    Creation site web August 25th

    thx for this tutorial, but how can i use it to submit a form into a database ?
    can you help me please ?

    ( Reply )
  200. PG

    Capricorn20 August 26th

    This is really good and is pretty much spot on for what I need. This method seems to work a treat for a single form. However what about when processing several forms on one page.

    My scenario is that I have some content that has an unapproved status and an ‘approve’ button to set the status.

    Is there a way to make this work or is this script limited to a single form?

    Thanks.

    ( Reply )
  201. PG

    Jay September 1st

    Well, with all the problems addressed in the comments, I don’t understand why the author has not updated this tutorial with all the fixes for people trying to learn. Thought this was a tutorial site? Shame on net tuts.

    ( Reply )
  202. PG

    francis September 1st

    What is the purpose of this lines on ‘process.php’?

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

    As far as I know “$mail = new PHPMailer();” object is sending the email further down.

    ( Reply )
  203. PG

    micrexazudr September 6th

    Dadloved the country club. lesbian group sex Sharon had a good that i was.She sobbed as the floor and his buddies. denise milani videos Themajor didnt saymuch.Now, you this lieutenant niurka marcos calendario desnudo was so i muttered in everyone.

    ( Reply )
  204. PG

    Petar Velkov September 11th

    Hi, I’m trying to build an AJAX search engine, working without any refreshing. So, I have a simple text input, a simple button and a div, where I show the results.

    But pressed once, the button stops working. Any ideas how to fix that?

    ( Reply )
  205. PG

    Adam Arnold September 14th

    Can we post data from a textarea with this method?

    ( Reply )
  206. PG

    ronaldo September 19th

    Good one…

    ( Reply )
  207. PG

    Lars September 22nd

    Great script. But is there any way how to display different messages to the user depending of php script result?

    It looks strange that “Contact Form Submitted!” will displayed even if php script for some reason doesn’t process the form.

    I will use this form in a section where some users are blacklisted and php script will not process their data. How do I display error messages generated by php script?

    Thanks,

    ( Reply )
  208. PG

    ng September 23rd

    Thankyou so much!!!!!!!!

    ( Reply )
  209. PG

    Mark September 24th

    Hi Nice tutorial,

    But i’ve added a drop down menu to it with couple of option, but when the form is submitted i don’t receive the option selected within the e-mail.

    I’ve also edited the template within the process php and added the var but still it comes out empty.

    Any suggestions guys?

    ( Reply )
  210. PG

    manhtrungit8x September 30th

    That good

    ( Reply )
  211. PG

    Monti October 1st

    Nice.
    Thx man

    ( Reply )
  212. PG

    Gopal Raju October 4th

    What about email validation?

    ( Reply )
    1. PG

      David October 6th

      I suggest to use a regoular expression or add the really powerfull Jquery form plugin

      ( Reply )
  213. PG

    Lou October 5th

    Thank you for your efforts in this area. I have adapted it to a website we have created in Dreamweaver. We wanted folks to be able to submit a request to us. We had one that worked great on our Microsoft environment but our service provider has a Linux server.
    Just one question where do we insert our email address for the submit to go to.

    Thanks again,

    ( Reply )
  214. PG

    David October 6th

    Congratulations, powerful and simple script.

    For the form validation I suggest you a very powerfull jQuery Plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/.

    What about security?

    If i submit a login form and I open firebug i can see the post parameters text, including password!

    Is there a way to avoid this?

    ( Reply )
  215. PG

    Chris Armour October 6th

    Excellent tutorial – Simple to follow. Just what I needed for my own site!

    ( Reply )
  216. PG

    coco October 7th

    nc tut

    ( Reply )
  217. PG

    m1k3y02 October 9th

    Hi There,

    As I have never fiured out javascript and still feel it’s a bit odd scripting language your tutorial helped me a lot

    Cheers!

    ( Reply )
  218. PG

    Michal October 12th

    is there any way we could use different function than (document).ready ?
    there seems to be a problem in case form is loaded via ajax into another div. It simply does not call the function.

    Any ideas how to solve this ?

    Thank You in advance.

    ( Reply )
  219. PG

    khaja October 15th

    very nice, i would like to say thanks

    ( Reply )
  220. PG

    baa October 21st

    your form is perfect except that it misses the email validation.
    I tried to put a piece of code myself but the form stops working.

    can somebody help me please?

    ( Reply )
  221. PG

    George Garchagudashvili October 22nd

    Nice tut, keep up…

    ( Reply )
  222. PG

    Tim October 24th

    Nice tutorial

    ( Reply )
  223. PG

    adam cleaner October 24th

    using this script on my website but it sn’t working exactly how i want (you’ll see what i mean when you submit), been working all this weekend hope to get it working soon as it’s a great script

    ( Reply )
  224. PG

    Chris October 26th

    This is great but is there a way to have the email validate so it recognises that its a proper email? Same with the phone field. Any way to validate that its numbers only?

    ( Reply )
  225. PG

    Chris Torres October 27th

    Solved it!!

    If you wish email validation change:

    if (email == “”) {

    in the tutorial.js with:

    if (email.lastIndexOf(”.”) <= email.indexOf("@")) {

    works a treat!!

    ( Reply )
  226. PG

    hiren October 27th

    very nice example
    thanks a lot

    ( Reply )
  227. PG

    Prashant October 28th

    I used this tut and works well but i have one problem.
    I used this for my cakephp application. I have 2 buttons on form when form is submitted i want to know which button is clicked. But I am not getting button value only form values getting. So how to get that????

    ( Reply )
  228. PG

    Jay October 29th

    thanks for sharing such a great form.. using in one of my sites now :D

    ( Reply )
  229. PG

    brackhuas October 31st

    wow, a lot of nitpicking going on here. if everyone in here can’t figure out how to do their own regex validation, and can’t figure out how to make an ajax app seo friendly, maybe you shouldnt be a web developer. rss feeds cover all your seo need without having to cripple your website back to 2001, for starters. and if you have javascript disabled you might be 100 years old or maybe stupid.

    ( Reply )
  230. PG

    memomium November 8th

    looked through every comment and the one issue that a handful of people bring up isn’t resolved.

    i dont think this works.

    ( Reply )
  231. PG

    mani ratnam November 10th

    Thanks a lot…

    ( Reply )
  232. PG

    Ika November 11th

    Great. 10x

    ( Reply )
  233. PG

    T. November 11th

    Cheers… gave me the start I needed.

    ( Reply )
  234. PG

    Gopal Bhattacharjee November 13th

    Hi Eric,

    Very nice tutorial, thanks a lot. But, I have some problem with email validation.
    I will try my self ….but not succeed …Please help me … I’m new in javascript/jquery……

    I need email validation code instead of this

    var email = $(”input#email”).val();
    if (email == “”) {
    $(”label#email_error”).show();
    $(”input#email”).focus();
    return false;
    }
    Regards,
    Gopalb

    ( Reply )
  235. PG

    Ryan Dearlove November 18th

    Thanks, sweet i’ve used something very similar on my website, Thanks.

    Great BLOG!

    ( Reply )
  236. PG

    Ethan Smith November 18th

    This is great, thanks!

    ( Reply )
  237. PG

    zfinley November 20th

    Pretty SICKK

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 20th