Ajax Forms with jQuery

  • Published: 09.08.2007
  • Categories: Tutorial
  • Comments: 404

There are so many different javascript frameworks out there, but I have recently started to use jQuery, and I love it. Not only is the library much smaller than others, but it is so simple to use. I wanted to show how easy it is to turn a regular form into a AJAX form.

Start with a Regular Form

First, I am going to build a regular form. The form is just going to be a basic email form. You enter an email address to send to, an email address to send from, a subject, and a message. All fields are required. So the process of the form is:

  1. User fills out the form.
  2. User submits the form to the server.
  3. Server side script makes sure that there are no blank fields and that the email addresses are valid.
  4. If there are errors, show the form again with the error messages.
  5. If there are no errors, send the email.

Ok, so this form is pretty simple, and doesn’t take much time to submit since it’s so short, but let’s see how much better we can make it with a little jQuery.

Add in JavaScript

OK, so next, I am going to make an AJAX version, which is a duplicate of the first form. The only other things I am going to include on the page are the jquery library (which you can download here) and my JavaScript to process this form.

Firing My Script When the Document is Ready

jQuery has a nice little function to have you script start when the document is ready:

$(document).ready(function(){
 
//Script goes here
}); 

OK, easy enough. Now, let’s make something happen when the button to submit the form is clicked. I was smart enough to add an id of submit to my button, so it makes it really easy to reference:

$(document).ready(function(){
 
$("#submit").click(function(){
  
return false;
 
});
}); 

First things first, I’m going to hide anything with the class of error if it’s showing (which nothing will be unless the form is unsuccessfully submitted twice). I also create a variable that I am going to use later to see if the form has an error and a variable to store the email regular expression:

$(document).ready(function(){
 
$("#submit").click(function(){
  
$(".error").hide();
  var 
hasError false;
  var 
emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  return 
false;
 
});
}); 

Error Checking

Now that we’ve got the beginning of the script setup, we need to do the error checking. So first, let’s check to make sure that the email to address is not empty or invalid:

$(document).ready(function(){
 
$("#submit").click(function(){
  
$(".error").hide();
  var 
hasError false;
  var 
emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  var 
emailToVal = $("#emailTo").val();
  if(
emailToVal == ''{
   
$("#emailTo").after('<span class="error">You forgot to enter the email address to send to</span>');
   
hasError true;
  
else if(!emailReg.test(emailToVal)) {
   
$("#emailTo").after('<span class="error">Enter a valid email address to send to.</span>');
   
hasError true;
  
}

  
return false;
 
});
}); 

Remember, the email address to send to input has an id of emailTo. What that code is saying is:

  • Get the value of the email to address input.
  • If it is empty, add an error message after the input
  • If it has an invalid email address, add an error message after the input.

Now, we just need to repeat the error checking for the other form fields:

$(document).ready(function(){
 
$("#submit").click(function(){
  
$(".error").hide();
  var 
hasError false;
  var 
emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  var 
emailToVal = $("#emailTo").val();
  if(
emailToVal == ''{
   
$("#emailTo").after('<span class="error">You forgot to enter the email address to send to.</span>');
   
hasError true;
  
else if(!emailReg.test(emailToVal)) {
   
$("#emailTo").after('<span class="error">Enter a valid email address to send to.</span>');
   
hasError true;
  
}

  
var emailFromVal = $("#emailFrom").val();
  if(
emailFromVal == ''{
   
$("#emailFrom").after('<span class="error">You forgot to enter the email address to send from.</span>');
   
hasError true;
  
else if(!emailReg.test(emailFromVal)) {
   
$("#emailFrom").after('<span class="error">Enter a valid email address to send from.</span>');
   
hasError true;
  
}

  
var subjectVal = $("#subject").val();
  if(
subjectVal == ''{
   
$("#subject").after('<span class="error">You forgot to enter the subject.</span>');
   
hasError true;
  
}

  
var messageVal = $("#message").val();
  if(
messageVal == ''{
   
$("#message").after('<span class="error">You forgot to enter the message.</span>');
   
hasError true;
  
}

  
return false;
 
});
}); 

Ok, error checking is done. If there are no errors, we need to send the email via an AJAX request. I’m not going to include the whole script here, just because it’s getting long, but you can see the whole script.

So, there are no errors. Let’s remove the button from the form, and add in a loading graphic:

if(hasError == false{
 
$(this).hide();
 $(
"#sendEmail li.buttons").append('<img src="/images/template/loading.gif" alt="Loading" id="loading" />');

Submit the POST Request

Ok, now let’s send the values via an AJAX POST request to our send email script that just sends the email. Once the request is completed, let’s hide the form and display a success message:

$.post("/play/jqueryAjaxForm/sendEmail.php",
   
{ emailToemailToValemailFromemailFromValsubjectsubjectValmessagemessageVal },
    function(
data){
  
$("#sendEmail").slideUp("normal", function() {

   
$("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');
  
});
 
}
); 

Pretty nice huh? So now, you have a perfectly accessible form. It works fine without JavaScript. But it works even better with JavaScript. I highly recommend checking out the jQuery Documentation. So go ahead, send yourself some emails to see for yourself.

Update…

I was asked in the comments if I could include the PHP script. So as requested, here are the files that are used:

404 Comments

Ronald Allan

09.08.2007

ei thanks! i will try this code.. actually i need this kind of code for my new project.

thanks again!

Dean

09.09.2007

Instead of tying your function to the onclick event of the submit button wouldn’t it be better to attach it to the onsubmit event of the form?

Trevor

09.09.2007

@dean
Well, you could definitely have the function fire on the onsubmit event of the form, but it shouldn’t function any differently.

Why do you think it would be better?

David Hemphill

09.17.2007

I was excited to see such a good example of jQuery’s ajax functions online. Well done.

The only reason I can see having the function fire onsubmit is in the case of the user hitting enter to submit the form.

Trevor

09.17.2007

Hmm yeah that’s what you would think, but the form still submits when you hit enter in a form field. I guess that makes sense.

I guess when you hit enter in any form field it acts as though the submit button is “clicked”.

huljo

09.19.2007

Is there any chance we can see the PHP script as well? I’m having a hard time wrapping myself around how this is listening for a successful execution by PHP. To make sure everything on the server executed as planned.  Or is this only client-side validation?

Trevor

09.19.2007

@huljo-
The PHP files that I used are now included for download at the bottom of this entry. Let me know if you have any other questions.

jack

12.20.2007

I can’t download the php files at the bottom. I’ve tried both on a PC and Mac with Firefox. Could you please fix this?

Trevor

12.21.2007

Jack-
Sorry about that, I think they got lost when I redesigned. Should be able to download them now. Let me know if you still have trouble.

Andy Bailey

01.21.2008

I have to tell you that this bit of code and explanation has caused a paradigm shift in my AJAX knowledge. I really appreciate you putting this post up and sharing your code. I have downloaded, edited and installed this to my current AJAX site project and it works really well. (I’ve already been praised for my ingenuity too, sorry, I didn’t pass the credit on!... :-P)

a big thumbs up!

Trevor

01.24.2008

@Andy-
Awesome! I’m glad that the tutorial was helpful. No worries about not giving me credit, anything to make the web a better place.

Jon Mallow

02.16.2008

I’m not an expert at Ajax and jQuery, but I’ve dabbled in them enough to think that I know what I’m doing.

However, I can’t seem to even be able to replicate this. I can copy all the files and even the pages you use on the internet and still not get this to work.

So what am I forgetting to do that isn’t shown on the website? are the form pages php or html? am I supposed to leave the s on phps? It started to work a little better when I kept the s on.

I’m just a wee bit confused, followed the instructions and made some custom fields in the beginning, but that didn’t work out, so i did a dumber down version, still didn’t work. Now that I can’t even get your version to work I know I’m doing something wrong :P

Thanks,
Jon

Trevor

02.16.2008

Jon-
Hmm, are you receiving any kind of error message? Do you have a page you can show us? The form pages could be HTML, but you would have to tweak a lot of stuff. The files that you downloaded need to be php, not phps. The phps files are source files, so that people can download them from the website. Let me know how I can help.

Paolo

02.24.2008

Thank you, Trevor, this has been very useful indeed. I am trying out a simplified form of this on http://new.taize.fr/en

I have one question, and one lingering concern:

In submitting the post request why use:  “function(data){” instead of just “function(){”—which in my case anyway, seems to work just as well (or does it?)?

Would it not be better to get an error message if, for some reason, the mailing fails (for example the php file is not found)? As far as I can understand from the jQuery doc this involves using $.ajax instead of $.post. And that looks complicated ...

Trevor

02.24.2008

Paolo-
Glad the example has helped.

In regards to your first question: “why use: function(data) instead of just function()

I guess I didn’t need to use function(data) in this example, but I just did. Basically, if the PHP script that I am calling returns anything, I can access that value. Like in the PHP file, if I put echo ‘hello’;, then if I add alert(data) inside of the JavaScript callback function, it will alert hello.

I guess my answer to the first question should answer your second question. You can certainly do some checking in the PHP file and return something if there is an error. Then just check the value of data in the JavaScript and see if there is an error.

Let me know if you need any other help.

Paolo

02.25.2008

Trevor, This all works.  jQuery is good, isn’t it? Clearly worth trying to learn properly! Thanks so much for the encouragement to do this.

Paolo

02.25.2008

Well, it all works—except for the case when the PHP file which does the mailing is not found. Then the whole thing seems to break down before getting as far as “function(data)”, and I cannot get it to supply an error message. That’s a minor concern, though.

Trevor

02.25.2008

Paolo-
So you are saying the PHP file doesn’t exist on your server? I mean the simple and obvious answer is to move it into the correct location. I may not be understanding what you are saying is the problem. Do you have a link that we can see?

Paolo

02.25.2008

“are saying the PHP file doesn’t exist” :-) No, no. It does exist and everything is fine. It’s just that, if it didn’t (say I delete it by mistake in 6 months’ time), the system is not going to flag that up.

At http://new.taize.fr/en
I do this:

$.post("squelettes/sendnews.php",
 
{ LanguageLangValEmailEmailValsubscribeSubVal },
  function(
data){
   
if(data){
    
$("#message").text('Your request was sent.');
   
else {
    
$("#message").text('An error occurred. Your request could not be sent.');
   
&hellip

which works fine.  If the script doesn’t find “sendnews.php” I would have liked to be able to display some kind of error message. That’s all. And it’s not a big deal. Perhaps this is what the jQuery site means about using $.ajax if you want to do error checking. I shall just be careful to make sure the file is in place!

Trevor

02.27.2008

Paolo-
Hmm, I see what you are saying now. You could just use the $.ajax function and check the error that is returned (if there is one). It is more complex, and thus I’m not sure if it’s worth the hassle. Just don’t delete the files that you need to successfully complete the request!

Jaffer Haider

03.10.2008

Nice example. From a Javascript code cleanliness point of view, it’d be better if you made a private function in the click listener, that checks if a form field is empty and sets the ‘hasError’ boolean to true, right?

I’ve recently shifted from Prototype to jQuery as well, and it rocks!

Fiqhi

03.16.2008

This is what I’m looking for! thanks trevor :)

Johan

03.18.2008

Hey!!

Thanks for this guide. :)
This helped me though my first AJAX. :D
...and trough non-jQuery-guide to make a Captcha. :)

Thanks! :D

A little tip: If you also uploaded the final PHP-code, it would be much easier. ;)

Trevor

03.18.2008

Johan-
I actually did upload the final PHP code. If you look at the end of the post, you can download them there.

Fabián

03.22.2008

It seems that the validation can only be done client-side, am I right?

Trevor

03.22.2008

@Fabián-
The javascript does handle the client side. But, if a user does not have javascript enabled, then the PHP script will handle the validation.

john

04.08.2008

Thank you for helping to educate newbies like me.
I noticed that your example is not using the JQuery Form plug-in which has the AjaxForm and AjaxSubmit methods. What are your thoughts on the benefits of using those methods? Are you planning to include them in any future tutorial?

Trevor

04.08.2008

@John-
Glad that the example helped you. Yes, I have used the jQuery form plugin before. I would say the one advantage to using it is that there are a lot of functions already built into that plugin. If you don’t want to get your hands dirty writing your own stuff, sure, I would recommend using it.

Martin

05.21.2008

Very good and useful , but it doesn’t work with Prototype JavaScript at once used in Lightbox.

Do you have an idea why? Thanks for answer, regards.

Trevor

05.21.2008

@Martin-
Do you mean that there is a conflict between jQuery and Prototype? The jQuery documentation has an item about Using jQuery with Other Libraries. Hope that helps!

Alex

06.10.2008

Hmm, are you receiving any kind of error message? Do you have a page you can show us? The form pages could be HTML, but you would have to tweak a lot of stuff. The files that you downloaded need to be php, not phps. The phps files are source files, so that people can download them from the website.

gg

06.11.2008

I could not find “jqueryAjaxForm”

gg

06.11.2008

And I could not find success message as I submitted the comment.

Keenahn

06.26.2008

This is an excellent intro to jQuery. Kudos!

-K

Darrious

06.30.2008

I was wondering if anyone knew how to get radio buttons working? I’m having a tough trouble with getting them to work.

Trevor

06.30.2008

@Darrious-
What do you mean you are having trouble getting them working? Do you mean on the JavaScript side? Are you assigning values to the radio buttons?

Darrious

06.30.2008

Yes, it is on the Javascript side.

I’ve tried both the original code:

var radio_btnVal = $("#radio_btn").val(); 

And some other code:

var radio_btnVal = $("input[name='radio_btn']:checked").val(); 

___________________
I’ve also tried to assign each different values.
As such:

<input type="radio"  class="other" name="radio_btn" id="radio_btn1" value=""   />  
<
input type="radio"  class="other" name="radio_btn" id="radio_btn2" value=""   /> 

___________________
The original code that didn’t work either:

<input type="radio"  class="other" name="radio_btn" id="radio_btn" value=""   /> 

I’m not sure exactly what jquery’s expression would be for radio buttons.

Trevor

06.30.2008

@Darrious-
I think that there are surely a bunch of different ways to achieve what you are trying to do. I made an example page showing this.

When you hit submit, it will tell you which radio button is selected.  Basically, I am just checking if the checked attribute is true for each radio button.

if($('#testRadioYes').attr('checked') == true{
 alert
('Yes is selected');

Again, there are a bunch of different ways to achieve this.

seb

07.06.2008

cool

james

07.19.2008

Hi,

I just came across your Ajax contact form tutorial. I’m having a little trouble. What is the “‘../../includes/analytics.php’? Where is this particular file? Every time I try to send a message I get on the index page this “Warning: main(../../includes/analytics.php): failed to open stream: No such file or directory in /home/content/k/h/a/khariwilliams/html/beego/indexer.php on line 28

Warning: main(../../includes/analytics.php): failed to open stream: No such file or directory in /home/content/k/h/a/khariwilliams/html/beego/indexer.php on line 28

Warning: main(): Failed opening ‘../../includes/analytics.php’ for inclusion (include_path=’.:/usr/local/lib/php’) in /home/content/k/h/a/khariwilliams/html/beego/indexer.php on line 28”

Can u please help me! Or send e-mail the exact codes the way created your mail form.

Trevor

07.19.2008

@James-
You can just remove that line from the code. It is just a file that contains my Google Analytics information. I guess I should have removed it from the source files.

josh

08.03.2008

Trevor,

Can you help me out a bit. I am looking for a way to use a for loop in a similar situation you demo’d
here:

But with the addition of more sets of radio buttons. I want to be able to have a function loop through the radio button sets and with a counting var keep track of how many are “checked”. Once the loop has gone through the length of the array of li’s or ? Another function then does something based on the counting var.

I can’t seem to get the for loop to work and I am not sure how to get around identifying each radio as an id?

Does this make sense?

If not email me and I will send you my code block.

Thanks for any help in advance if you have time I’d appreciate the learning exp:)

benjamin

08.25.2008

hi trevor!
your site is just great. thanks a lot for sharing so good inputs. may i ask you, how you transmit the values of select-items with ajax-forms with jquery?
cheers!
greetings, benjamin

Trevor

08.25.2008

@Benjamin-

You would do it the same way you would any other input field.

$('#idOfSelectHere').val(); 

Christoph G.

09.02.2008

Thanks a lot for sharing so good inputs!

Chris

09.02.2008

Hey there. Thanks so much for supplying this code for everyone to use. I am somewhat of a newbie to forms and suck, and was wondering if you could help me out. I have this code on my contact page here:
http://dev.creativehinge.com/contact.php

I also have the four files you supplied here:
http://dev.creativehinge.com/form

How do i get this started? I hit submit and it looks for the “/play/jqueryAjaxForm/” directory. What do I place in this form action acrea? I want to achive the following:

1.Remove the option of entering an email address. All emails should go to to .(JavaScript must be enabled to view this email address)

Thanks for any help you can provide.

Trevor

09.02.2008

@Chris-
Change the form action on this page to point to itself. So change it from /play/jqueryAjaxForm/ to /form/.

Remove all of the information regarding the emailTo form element and update line 9 of sendEmail.php to read:

mail('info@creativehinge.com'$subject$message"From: ".$mailFrom); 

Hope that helps.

Chris

09.02.2008

Hey, thanks so much for that line of code. I’ve made the two changes, but i’m still unsure of a couple of things. I’m embedding the form in my contact page here:
http://dev.creativehinge.com/contact.php

So technically i wouldn’t even need the index.php page in the forms/ directory. Can i remove this file from the folder?

Then, on my contact page, Change the form action to point to itself. So change it from /play/jqueryAjaxForm/ to /form/?

Also, is the “/” necessary before the folder “form”?

Thanks SOO much…

Trevor

09.02.2008

@Chris-
You basically want to take all of the coding from index.php and put it in contact.php. Then reference the other PHP files appropriately. So you would change the form action to be contact.php now.

Chris

09.03.2008

Hey there,

It doesn’t seem to be sending the emails when i click submit, nor does it pull in the thanks.php info. I know it’s something really silly i’m not doing on my part….could you take a look? I hate to be a pain.

Here’s the link again:
http://dev.creativehinge.com/contact.php
the other files are in this directory:
http://dev.creativehinge.com/form/

Again, Thanks so much.

Chris

Trevor

09.03.2008

@Chris-
It’s hard to debug it without looking at the PHP. Did you remove all traces of emailTo in verify.php? It looks like you never get to the success state.

Chris

09.03.2008

no i never removed code from verify, just the frontward facing entry box. should i delete that whole first chunk:

if($_POST['emailTo'== ''{
 $emailToError 
'*Oops. We dont know your email.';
else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$"$_POST['emailTo'])) {
 $emailToError 
'Enter a valid email address to send to.';

Thanks

Chris

09.03.2008

here’s all my verify code:

Chris

09.03.2008

I’ve never gotten forum/blog advice before, so i appreciate all the quick replies! Just tried to place a chunk of code in there, and it seemed to eat it up. Whats the trick you use to get code up here?

Also, what can i send you to help you get a better idea?

thanks

Trevor

09.03.2008

@Chris-
Yes, just remove all of this from verify.php:

if($_POST['emailTo'== ''{
 $emailToError 
'You forgot to enter the email address to send to.';
else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$"$_POST['emailTo'])) {
 $emailToError 
'Enter a valid email address to send to.';

Then, change line 22 of verify.php to be:

if(!isset($emailFromError) && !isset($subjectError) && !isset($messageError)) 

That should do it.

Chris

09.03.2008

I think my main issue is with my verify code:

(this is wrapped in a php tag)

if(isset($_POST['submitted'])) {
 
if($_POST['emailTo'== ''{
  $emailToError 
'*Oops. We dont know your email.';
 
else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$"$_POST['emailTo'])) {
  $emailToError 
'Enter a valid email address to send to.';
 
}
 
if($_POST['emailFrom'== ''{
  $emailFromError 
'*Oops. We dont know where to send it.';
 
else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$"$_POST['emailFrom'])) {
  $emailFromError 
'Enter a valid email address to send from.';
 
}
 
 
if($_POST['subject'== ''{
  $subjectError 
'You forgot to enter the subject.';
 
}
 
 
if($_POST['message'== ''{
  $messageError 
'You forgot to enter the message.';
 
}

 
if(!isset($emailToError) &amp;&amp; !isset($emailFromError) &amp;&amp; !isset($subjectError) &amp;&amp; !isset($messageError)) {
  
include('form/sendEmail.php');
  include(
'form/thanks.php');
 
}

Chris

09.03.2008

Excellent! I get the success message! This is all very good, what wonderful code.  Just a couple more questions, as i dont seem to be actually getting the emails though it might be my webapp. just wanted to make sure the code is functional.

here is the code from sendemail.php:

$mailTo $_POST['emailTo'];
$mailFrom $_POST['emailFrom'];
$subject $_POST['subject'];
$message $_POST['message'];
   
mail('christopher.homan@gmail.com'$subject$message"From: ".$mailFrom); 


Is this right?

Trevor

09.03.2008

Chris-
Yep, that should still work. I would remove this line since you removed the emailTo field:

$mailTo $_POST[‘emailTo’]

Chris

09.03.2008

Hey Trevor. I removed that line of code from verify. I also changed my email address to my gmail just to make sure, but am still not receiving emails. It pulls up the success info, but i just dont get an email. I assume the link in verify to sendemail.php works as it pulls in thanks.php…any ideas?

Trevor

09.03.2008

Chris-
I’m not sure what to suggest at this point. Since you get all the way to the thank you message, there is no error in the code. Does your server have a mail server specified? Is it going to your spam folder in gmail? Are you sure you have your email address correct?

Chris

09.03.2008

Does your server have a mail server specified?
Maybe. I tried to set up gmail apps, as well as emails for my domain, but ran into some snags. There’s a step that requires me to change my cName record, something i have to put a ticket in to do. I keep putting in ticket requests, but mail.creativehinge.com just doesn’t seem to be working. Anyhoo, thats another ish.

Thanks for all your help!

Kerwin Groot

09.11.2008

I’ve had some poking out on this thing aswell so maybe i can help a bunch of you guys out by sharing my packed version of the form.

It’s has got the “Email To” field removed, because all mail in my contact form should go to me.

The only setup it needs is to replace the dummy adres with your own in “sendemail.php” at the bottom.

And optionaly: if you change the directory name (by default “contactForm” you should change the form action parameter located in index.php accordingly.

Thkx Trevor for making this form, saved me a lot of time!

The file: www.kerwin-groot.nl/upload/contactForm.zip

Rafa Garcia

09.12.2008

Simple as good things are.

Dave Brookes

09.25.2008

@ Kerwin Groot

Hi Kerwin,

Using your ziped example emails don’t seem to get sent when JavaScript is disabled, can you confirm that you are defiantly receiving emails from none JavaScript clients?

Thanks,

Dave

Federico

09.27.2008

Great script trevor, thanks for your effort.
Just a couple of questions:
how to modify the senEmail.php code to improve security? Maybe using somke trick like the following one: http://15daysofjquery.com/examples/contact-forms/

About the php feedback code, like this one:

if(data){
 
$(“#message”).text(‘Your request was sent.’);
else {
 
$(“#message”).text(‘An error occurred. Your request could not be sent.’);

I don’t understand exactly how I could show in the contact form page how to display a message sent by the sendemail.php file if in it I use some echo message.

Thanks a lot for reply

Trevor

09.27.2008

@Federico-
Sure, you could make the contact form more secure, but if you are just using it to send an email and not interacting with a database, it may be a lot of extra effort for not much benefit.

Regarding the code snippet you included, you just need to have an element with the id of message, and the text will be changed depending upon the condition. Does that answer your question?

Federico

09.28.2008

Thx for reply Trevor.
About the code snippet, the question is: how do I get and print some text returning from the PHP server file?
I know that I have to add an id “message” in the web page but I don’t understand how can I pass some text from the php to a $(”#message”).text variable instead a fixed text.
Hope I explained..sorry for bad english!

Trevor

09.29.2008

@Federico-
In the PHP file you are calling via the POST request, you can just echo something out. Whatever you echo out, will be available in the data variable:

$.post("/play/jqueryAjaxForm/sendEmail.php",
   
{ emailToemailToValemailFromemailFromValsubjectsubjectValmessagemessageVal },
    <
strong>function(data){</strong>

 
}
); 

Jake Rutter

09.30.2008

Great Tutorial! Thanks!

Joe

10.06.2008

Hi Trevor,

Thanks for this great tutorial. A question: I would like to add a “Your name” field, si I would have “Your name”+“Your email address”+“Subject” and the message.

I tried to do this, no problems to add this additionnal field, to verify it etc… but in the mail I don’t receive the name of the sender…
Is it possible ? Please could you help me ?
(Sorry for the bad english)

Trevor

10.06.2008

@Joe-
You will need to modify the sendEmail.php file and add in your new fields to the email.

Clemente G

10.09.2008

How can you use this to work with wordpress? I have the contact working it sends the email. I have contact.php embedded into a div on my main page. The problem is it reloads the whole page and the posts do not show.

Any suggestions??

Trevor

10.09.2008

@Clemente G-
Do you have a link I can take a look at?

Joe

10.13.2008

Thank you Trevor ! Another question: I’m french and unfortunately we have some accents in our alphabet…
When I receive a mail including accented letters, I have some strange characters like “é” instead of “é” for example.
Is there a coding solution to avoid this problem ?

Trevor

10.13.2008

@Joe-
You could change the email to be an html email instead of just text. Then use the htmlentities function to convert all characters to the appropriate entities.

Joe

10.13.2008

I’ve found a solution Trevor. Thank you.
In sendemail.php I’ve changed:

$message stripslashes (utf8_decode ($_POST['message'])); 

It’s not very “artistic”, but it works ! ;-)

Eduardo

10.14.2008

Hi Trevor,

Thanks for the excellent tutorial, I have just started to use jQuery a couple of days ago.

I have downloaded the PHP files but I don’t see where the jquery code is being loaded? I see that the error messages are output when something is not filled out, but I believe it’s all the PHP errors generated by index.php. How can I know the form is being sent via ajax?

Eduardo

10.14.2008

Never mind my previous post, I attached jquery.js and your submitform.js files and it works like a charm.

From what I understand your script only does form validation, but not form submission using Ajax, am I correct?

Trevor

10.14.2008

@Eduardo-
No, it does submit the form via an AJAX request.

Eduardo

10.15.2008

Thanks Trevor I noticed it does work, for some reason when I can get your script to work on a sandbox site but on the one I actually want it to work, when the sendemail.php script is called by $.post I get a 403 forbidden error, but the server validation does work, and it does send the email, do you know how I can get past this?

Trevor

10.15.2008

@Eduardo-
Are you sure you have the POST request submitting to the correct URL? So you said it works without JavaScript?

Eduardo

10.15.2008

Hi Trevor, yes the URL is correct and it does work without Javascript, I am using a CMS could that be the problem? but I load my form via an include and it loads it fine and as I said it gets sent without JS.

Eduardo

10.15.2008

Ok I figured it out, my CMS had a .htaccess file that was blocking the script in the folder I was trying to access!.
Thanks again!

Trevor

10.15.2008

@Eduardo-
Nice, I was going to suggest something was up with the config. Glad you got it working.

amir

10.17.2008

thanks

hm2k

10.20.2008

Beware of email injection with php’s mail() function, google it.

Eduardo

10.21.2008

h2mk:
Good point, but wouldn’t the server side regEx validation for email address be enough to be safe?

Martin Edwards

10.23.2008

Hi Trevor,

Thanks for putting this together, it’s helped me out loads. I love JQuery, but had never used it in conjunction with AJAX.

I made a small tweak to the PHP, to help with validation:

if (mail($mailTo$subject$message$headers)) {
 
echo "Success";

This passes it back to the JS as the ‘data’ variable, then I could give a bit more feedback:

function(data){
 
if (data == "Success"{
  alert
('success message here');
 
else {
  alert
('failure message here');
 
}

Eduardo

11.18.2008

Trevor:

I am having trouble with a checkbox, in my form I have <input value=”Yes” >
Which means whenever it’s checked the value is set to Yes, and this works perfectly with my server side validation and php’s “isset” function,

However, whenever I pass the .val() of that checkbox via jQuery’s AJAX, the value is ALWAYS “True”, how can i fix this?

Trevor

11.18.2008

@Eduardo-
Actually, this is a similar problem that Darrious had.

Check out the sample page or see my response to Darrious.

Eduardo

11.18.2008

@Trevor:
Thanks for your answer, it was kind of a similar problem.  However I fixed it by instead of using this in my php email script:

if(isset($_POST['mycheckbox']{...

using this:

if ($_POST['mycheckbox'== "Yes"{...

This is because for some reason jQuery always returns a value for “mycheckbox”, probably “” <—empty, but isset then returns true. Not a problem within jQuery code at all, but it became an issue when processing my email script.

Maybe someone else will find this useful.

Martin Baker

12.01.2008

Thanks for posting this, it’s a great starting point for a jQuery newbie. I’m a bit confused what purpose the thanks.php file has though because the “Success. Your email was sent” text appears to be set from the javascript rather than the contents of this file.

Trevor

12.01.2008

@Martin Baker-
The code in thanks.php is for people who do not have JavaScript enabled.

Remember, you always want to have a non-javascript alternative.

Aaron

12.11.2008

Trevor,
Thanks for the article, this solved a problem that had been bugging me for weeks.  Now that I’m using your method, I had a weird thing happen.

I entered an incomplete email address and submitted.  This caused the form to submit as though js wasn’t enabled.  Now the form won’t submit via ajax.  I don’t know enough about either to have any idea where my problem might be.

Any help or guidance you could give would be greatly appreciated!

Trevor

12.11.2008

@Aaron-
Do you have a link to the page? Are you getting any JavaScript errors?

Aaron

12.11.2008

Asking for help is always the silver bullet for me.  All is working now.

Thanks for being willing to help me out!

Trevor

12.12.2008

Hey, at least it’s working now!

Mehmet

12.13.2008

Trevor, I love the web as much as you do. See, I was looking for a way to use jquery and php to send mail and I’ve found your post. Thanks!

Michael

12.16.2008

nice tut

dnnsldr

12.18.2008

I am wondering if you (or anyone) would have the:
else if (!eregi -in order to validate a US Phone Number. Great scripts. Thanks,

Trevor

12.18.2008

@dnnsldr
It looks like after a quick Google, this site has a library of regular expressions, including US phone number.

dnnsldr

12.18.2008

@trevor
Thanks for your help. I am not a programmer, so my search was for phone validation, and non of them really seemed to fit the format. The website you recommended was great! Thank you,

Marc Falk

01.06.2009

Has any of you had any problems with this code in Internet Explore 6 or 7 ?

Thanks in advance..

Trevor

01.07.2009

@Marc Falk-
What kind of problems are you having? Do you have a link you can show us?

Marc Falk

01.07.2009

Well, when I have sent an email with the script the “thank you”-message doesn’t appear in IE6 or in IE7. It’s probably a question of my css doing something it shouldn’t, but I can’t find out what the problem is.

You can take a look here:
www.marcfalk.com/newluciti/competence.php

or here:
www.marcfalk.com/newluciti/contact.php

Both forms are supported by this script, and you can send all the test messages you want :P

I appreciate your time…

Trevor

01.08.2009

@Marc Falk-
Hmm, nothing immediately sticks out to me. It looks like your html that you are inserting could use a little cleaning up. It looks like you have some extra tags in there.

Try taking the code that you are inserting via JavaScript, and just putting it on the page where it was being inserted. Then see if it displays in IE.

I don’t think it is a JavaScript problem.

Xavez

01.09.2009

Thanks a million for your very easy to follow introduction to AJAX forms!

Andrew

01.13.2009

Thanks a million for the script. 

Was wondering how you would pass checkbox values through submitform.js to sendemail.php. 

For example I am using a form array.

Trevor

01.13.2009

@Andrew-
This is a similar question that Darrious had.

Check out the sample page or see my response to Darrious.

osu

01.14.2009

Hi Trevor,

Thanks for this code, much appreciated.

Just a quick question - I’ve got everything working on the PHP side, just trying to get the last part of the puzzle to work - Javascript.

All the error checking is working ok, so it’s the post path that I think is the issue (I’ve always had issues with paths, never quite got the concept as the way it works seems to differ between PHP, and Javascript).

Could you take a look at this code and let me know if there’s something wrong with it?

http://senduit.com/70e8e9

Thanks for any pointers

Trevor

01.14.2009

@osu-
It’s a little hard to only look at the JavaScript to try and figure out what is wrong. Are you getting any JavaScript errors? What happens when you click submit? Can you give us a link to the page?

mindcrash

01.17.2009

Thanks, your post was very useful!

osu

01.17.2009

Hi Trevor,

Thanks for getting back to me. You can download the site files here to test if you like:

http://senduit.com/867a47

I can’t show you a live copy because my client asked me to keep the site private for the timebeing.

Thanks

osu

01.17.2009

Oh, and when I click submit, everything works - including the JQuery slide up and success message, but no email is sent. When disabling JavaScript, the form validates and sends as it should, so I must be making a mistake with the end $post step I think.

Cheers

JK

01.17.2009

Trevor Wrote
@Dean
Well, you could definitely have the function fire on the onsubmit event of the form, but it shouldn’t function any differently.
Why do you think it would be better?

John@Trevor
Trevor, Dean is right - many if not most people submit forms using the Enter key rather than by pressing a submit button.
And though it’s less important, capturing the form submission rather than a button click is semantically/thematically better too.

Trevor

01.17.2009

@osu-
Do you have FireBug? Do you get a JavaScript error? Can you see that the POST request completed?

Is this really where the files exist?
/subfolder/nominate/02-nominate-send.php

@JK-
True, but the form works even when you click enter as well. Which I why I was wondering what the difference is. I guess jQuery is smart enough to add in that functionality as well.

osu

01.17.2009

Hi Trevor,

Thanks for getting back to me. Yes, the files do exist in that directory and I also have Firebug installed which shows no Javascript error when the submit button is pressed.

Like I said earlier, the email sends fine when disabling Javascript, it’s just when Javascript is enabled that nothing seems to be sent out (I find it really confusing, because I’d expect to see a Javascript error).

Any other ideas?

Chris

01.18.2009

This is a nice example, but you’re running a php script that sends emails that is openly accessible this way right?  If you don’t protect the sendemail.php script on your server and some spammer locates it, your server is going to become a spam-mailing slave. 

The best way is to implement something that verifies the user to be a person (like those annoying “type what you see in the box to continue” prompts).  Also you’re not calling verify.php from the sendemail.php script, any particular reason?  If the client isn’t verifying the content submitted then neither is the server (this would happen if the javascript was changed on the client, a possible circumstance).  This shouldn’t be a problem if you just pointed your javascript code to use index.php instead, it would work the same as if javascript wasn’t working.

When I used prototype before, I would just use the $(form).request(...) which made a regular form submit as an ajax request (this could just be hooked to the form.submit() event.  There’s probably a jQuery equivalent, but I haven’t needed to look it up yet.

Just my 2 cents.

Trevor

01.18.2009

@osu-
Do you see that the POST request completes successfully or not? It should show up in the console after you have successfully submitted the form.

@Chris-
I agree, there are definitely some improvements to make to this. I wrote this well over a year ago when I was first learning about AJAX so I have learned a lot since then. I should probably write an update to it. Thanks for the input though.

osu

01.18.2009

Hi Trevor,

I’m almost 100% certain that the path is my issue. How should I be putting in the path in the $post part? i.e. should I put:

$.post("http://www.domainname.com/subfolder/nominate/02-nominate-send.php"

or maybe

$.post("/subfolder/nominate/02-nominate-send.php"

The response I get from Firebug in the console with the latter option is this:

1232324144764 lori -   OOB-RESPuri=http://www.domainname.com/subfolder/nominate/02-nominate-send.php, delta=314 

...to be honest, I have no idea what that means! Uncle Google didn’t help either…does it mean anything to you?

osu

01.18.2009

Ok, I figured it out. It was to do with a bit of php coding in my send script that was trying to prevent spammers from using a different URL to send emails out with my form. I guess I’ll have to lose it.

Apologies for wasting your time, thanks for being so responsive.

osu

Andrew

01.19.2009

How would I replace the entire form with the ajax loader image instead of replacing just the submit button?

Trevor

01.19.2009

@Andrew-
Instead of this:

if(hasError == false{
 
$(this).hide();
 $(
"#sendEmail li.buttons").append('<img src="/images/template/loading.gif" alt="Loading" id="loading" />');

Try something like this (substituting the id of your form if it is different):

if(hasError == false{
 
$('#sendEmail').slideUp('fast',function() {
  
$(this).after('<img src="/images/template/loading.gif" alt="Loading" id="loading" />')
 
});

Andrew

01.19.2009

Thanks very much.  is it possible for the ajax loader to only display while the form is sending then display the Success message?

Trevor

01.19.2009

@Andrew-
Sure, you would just want to remove the image once the POST request is complete.

Andrew

01.20.2009

Thanks

How would I remove the image?  Just hide ‘fast’ id again?

Trevor

01.20.2009

@Andrew-
Yep, just hide it or remove it.

espd

01.22.2009

Hey Trevor, great script.

I’ve been working on integrating it into a JQuery-powered drawer I got elsewhere, but having a problem.

Take a look (click the “Contact” tab to see where your form is):
enews.org/v6/portfolio/web/chow-trevordavis.php

The problem: When I put the form anywhere else on the page, it works fine (JS error checking works, form sends email), but when I put it into the drawer, it stops working.

I think there’s a conflict with the JS for the drawer action (“drw-scripts.js”), but I’m pretty lame at JS, so I’m at a loss.

Note that I’ve modified your files here and there.

Help would be magnificent.

Trevor

01.22.2009

@espd-
Yep, it is the drawer script that is causing the problem. If you take a look at the what drawer code is actually doing, it is taking everything in the div you have specified, copying it, and appending it in a different place.

If you use Firebug and inspect the page, you can see it duplicated in the source code.

espd

01.22.2009

Sorry, I’m just not very good at JavaScript.

So you’re saying the drawer script is copying everything in div #contact and moving it into div #drw. I see that, but why does that break the form?

Can you recommend a way I can still do what I’m trying to accomplish?

Trevor

01.23.2009

@espd-
Yes, you are correct in your assessment of what is happening. That breaks the form because you are binding the JavaScript event before the form in the drawer even exists.

Instead of using the drawer script, just use jQuery to slide the form down once the contact link is clicked.

Chris From Detroit

01.23.2009

can’t you just use $(form).serialize() ?

Andrew

01.26.2009

Hi Trevor.  I have been trying to hide the form with the ajax loader image and then replace it with the confirm text and I am really struggling.  I was wondering if you could give me a walk through of how its done.

Thanks a million

Trevor

01.26.2009

@Andrew-
What are you struggling with? What is happening? I already gave some instruction;  I’m not sure what I else I can do.

Without seeing exactly what you are trying to do, me just suggesting things doesn’t seem to be helping.

jb

02.04.2009

this is good

Rolli

02.07.2009

Impressive !! Just what I was searching for.

Skoua

02.11.2009

Thanks for this tut’.

Is there a way to check via Ajax if the mail was correctly sent or not ?

Thanks again.

Trevor

02.11.2009

@Skoua-
This has been discussed in previous comments.

paco

02.13.2009

Trevor…

Huge props, this is just what I was trying to do. I was able to download the files and get it up and running in minutes and thanks to your break down and patient replies to comments I can fully comprehend the awesomeness.

Let me buy you a cup coffee ya?
Peets or Starbucks? I’m not even kidding.

Trevor

02.13.2009

@Paco-
Excellent, glad you have found it useful.

Haha well, I don’t drink coffee, but you can feel free to donate to me if you really want to.

TG

02.13.2009

Trevor,

Just a couple questions please, do I need a server to run the files? What program or do I need a program to edit the php files? What type of license, no I didnt read the string of messages in the forum, do you require? Do you offer a tutorial for editing the files? Thanks for all your work on this.

Trevor

02.13.2009

@TG-
Yes, you need PHP to execute the PHP files. The form could easily be customized to use another programming language though. Any text editor should be fine for editing the PHP files. I don’t require any license to use the code.

What kind of questions are you having with editing the files? Feel free to ask or read previous comments to see if they answer your questions.

TG

02.13.2009

I’ve opened the files with notepad and I am lost. Im very new at scripts, php files and the like.

I did notice in the index php file that there was a css file(?) is that the css file I am currently useing, or is there one you have for the php files.

Also, I use webuilder, this code pops up in the input fields “” when I preview the page.

Where do I edit the files so the email gets to me? Sorry, I am very new to all this but need a secure contact form, and yours looks like one of the best I have found. Thanks for all your help

Trevor

02.13.2009

@TG-
The CSS file that I am referencing is this one. You could easily switch it out for your own though.

You have to have a server to execute PHP files. My guess is that Webuilder is just previewing the files locally so the PHP code is not actually being executed.

You want to change sendEmail.php so that the email gets to you.

I would recommend reading the comments above as they may answer some questions about changing the form so that the emails go to you.

TG

02.13.2009

Trevor,

Thanks for all the help

mark

02.17.2009

I am looking to add a contact form in a wordpress template I am designing and do not want to use a plugin.  Do you have any direction on how to use your form in a wordpress page?

Trevor

02.17.2009

@Mark-
I’m actually planning on writing a tutorial about doing that in the next week or so. Stay tuned.

Maria Mingosmo

03.05.2009

Hi Trevor

First of all thanks for the tut and the php files.

This is just the one script I was trying to create, but with no sucess (newbie girl) but you just made my life a lot easy.

Just one thing, but something really important to me: How can I redirect a user to a custom thank you page (I need to track conversions) instead of showing a thank you message like the one you have (‘SuccessYour email was sent.’)?

This is quite important to me, because if I can´t implement this redirect, I will not be able to use your superb code! :-( As I said Convension issues you know…

Kind Regards

Maria

Maria Mingosmo

03.05.2009

Just one thing, but something really important to me: How can I redirect a user to a custom thank you page (I need to track conversions) instead of showing a thank you message like the one you have (‘SuccessYour email was sent.’)?

This is quite important to me, because if I can´t implement this redirect, I will not be able to use your superb code! :-( As I said Convension issues you know…

Kind Regards

Maria

Maria Mingosmo

03.05.2009

Sorry for double/triple posting, my bad.

I forgot to mention that my question has to do with the client side validation of course and the need to redirect a user after the form is properly validated by javascript.

Sorry if my question is ridiculous, but I had to ask it anyway, I am a brave woman (or just dumb) !

Any help at all is appreciated ;-)

Kind regards

Maria

Trevor

03.05.2009

@Maria Mingosmo-
I would remove the AJAX functionality then. So the JavaScript validation will still take place, but then the form would be processed normally once there are no JavaScript errors.

Let me know if that doesn’t make sense.

Maria Mingosmo

03.05.2009

Thanks Trevor I see what you mean and unfortunately It makes sense. Removing ajax would make the form loose half of it’s glamour ;)

Let me try to make some changes and I’ll get back to you. I will be glad to keep you updated about this, afterall i’ll be working YOUR code.

Thanks again Trevor

Kind Regards

Maria

Shahar

03.06.2009

Hello,

I’m trying to use your script to include 2 forms in one page. However, only the first works. The other returns “The page cannot be found” on /play/jqueryajaxform/

These are two different forms, therefore I will need to declare different validations rules as well.

Your advice will be highly appreciated.

Trevor

03.06.2009

@Shahar-
Do you have a link to the page?

Shahar

03.06.2009

Wow! you are fast!

there you go:
http://test.tilldawndesigns.com/example/index.html

The form in home page works while the one in contact doesn’t.

Thanks!

Trevor

03.06.2009

@Shahar-
The problem is probably because you have an ID included on on a page multiple times.

The submit button of both of your forms has an ID of submit. I would change it to a class and then change it in the JS as well.

Shahar

03.06.2009

Thank you so much, works like a charm.

dnnsldr

03.09.2009

@Maria Mingosmo
Maria, I had a similar request resently and used google analytics to solve the problem. I have three different forms on the site and wanted to track not only the pages, but also the when the form was sent. You will need a google analytics account and then set up custom triggers, then in the submitform.js add:

// trigger Google Analytics goal for this submission
  pageTracker._trackPageview(”/thankyou_contact”);
  }

right before the “return false” at the end of the script.  the “thankyou_contact” can be anything you want, but basically you are telling google that you want to know when the form has been submitted. Works great. Hope this helps

Shahar

03.09.2009

Hello again,

I have a silly question but since i’m not a php developer i couldn’t figure it out.

I’m trying to add fields to the form,  how do i add variables to: message: messageVal? For example I have a website val. Not sure what’s the right syntax.

Thanks, Shahar.

dnnsldr

03.09.2009

@Shahar
Trevor gave me a great website before for Reg Expressions:
http://regexlib.com/DisplayPatterns.aspx?cattabindex=1&categoryId=2

It should be able to help you out.

Shahar

03.10.2009

Thank you but my needs are much more basic, I want the message field to include additional vars than messagevar.

{ emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal }

not sure what the right syntax for that.

Btw, I don’t need validation for these fields…

Thanks again.

Trevor

03.10.2009

@Shahar-
emailTo: emailToVal

That means that the POST variable that the server side script is looking for is named emailTo, and emailToVal is the value. You can actually just use the jQuery serialize function to get all elements of the form, and then pass them to the server side script.

You can see this function in action on my most recent article: [url=“http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/” rel=“nofollow”]
WordPress & jQuery Contact Form without a Plugin[/url].

Willabee

03.10.2009

Having followed built your application and on seeing what it does, I can conclude that there is a lot of unnecessary code and you are breaking the golden rule, whether you do client-side validation or not, you MUST always do server-side validation so…

All you need to do is add the nice client-side validation, get rid of all the XHR stuff (Not required for this app) and on successful validation, return true from the forms onsubmit handler.

It will then go off and do the server-side validation (Just in case someone interferes with the form data en-route) and check out the data before sending the email (calling sendmail.php directly with an XHR circumvents your server-side security checks). You might say sending email is not that much of a security risk but the application logic is teaching bad practises.

If the user disables or does not have JavaScript then the appliacation will function correctly but without the client-side validation saving round trips to the server on every submit attempt.

Perhaps a better opportunity of demonstrating how the client and the server might share the same code (sendmail.php in this case) would be to share the same set of validation rules, either injected at server-side during page generation as a JavaScript object or called from the client with an XHR request as, perhaps, the same JSON object that the server code used for its validation.

paco

03.10.2009

@Willabee

I appreciate your candidness, would you mind posting an example of your proposition?

What makes Trevors example so valuable is the thorough description of whats taking place along with actual code which ultimately leads to a functional example that we can put in our pocket and take home to further experiment with.

If I’m learning bad practices it would be great to see where I could improve and how.

Cheers.

Shahar

03.11.2009

Thanks man

Willabee

03.11.2009

@Paco - This reason I made my comment is that I feared, as your comment has confirmed, that folk will take this tutorial, as is, and put it into practise, without being aware of the consequences.

Trevor was a brave man to post his server-side scripts, which revealed flaws in the application that his students should be aware of.

I cannot respond with a tutorial and examples but let’s analyse what was wrong with the app’ and how we should approach writing web 2.0 app’s.

Step One - is to create a fully functional app’, where the user can post data to the server. The server will carry out sanitation and validation to make sure the data is good before continuing with its process.

Trever’s app passed this test.

Step Two - is to give the client some nice presentation by adding CSS (from an external file so that it will cache and be re-usable). Switch off CSS and the app still works.

Trever’s app passed this test.

Step Three - is to take over from the default user agent action and do some nice enhancements, such as dynamic DOM manipulation and client-side validation, to make the app’ more usable and avoid having to keep posting data to the server, the server checking the data is bad and having to return the form with all its content and any error messages (Every mistake followed by a submit was costing a round-trip to the server). Client-side validation at least ensures the data sent is good and less likely to be rejected). Switch off JavaScript and the default action (step one) still works.

This is where Trever’s app broke down, although most of what he has shown us is good.

To fix the app, remember, the default action when you submit a form (or press enter whilst focused on the form) is to post the form.

Trevor, quite correctly, takes over from the default action by adding an onsubmit event handler to the form. Now, instead of posting, control jumps to the event handler. As long as the event handler returns false, the for will not submit.

Trevor’s event handler always returns false.

He validates all the form fields, which is good, but then decides to post the form data by passing it to sendmail.php via an XHR object. This is the unnecessary code and bad practise I was talking about.

All that is needed after each field had passed its validation check is to return true from the onsubmit event handler. Now the form will carry out its default action, post the data, server checks (again because someone might have tampered with your data) the data is still good, processes and sends your email.

Luckily, Trevor did have some protection in sendmail.php but there was no validation. He could have duplicated this effort but that’s bad.

His protection was using $_POST[‘fieldname’]; in sendmail.php. Imagine if one of his students decided to use $_GET[‘fieldname’]; or even worse, $_REQUEST[‘fieldname’];, this would make it very easy to write a spammer that would loop through a database of target emails and call http://yourdomain/sendmail.php?field1=’$email[$i]&.....

You have just become a relay for spam mail. Because of $_POST[‘fieldname’];, the spammer would have to do a little more work but no problems.

By sending true to the onsubmit handler, we would at least validate the data (without any duplication of effort). Now we can add extra security, such as holding a session variable that we can use to see if the same user is continuously submittng emails so we can put a block on their email and IP address. The focus for security is in one place.

To my mind, we should not be trying to create an email client without careful consideration of all the threats and functionality that would be required.

It would be much more practical (and real world common requirement) to hard code the recipients email addresses at the server. Thus Trevor could have demonstrated all the nice jQuery client-side validation to post sales information and email it to your sales team.

I hope that is enough information to fix the application.

Trevor’s Application is good and passes all the tests except returning true after client-side validation success.

Willabee

03.11.2009

so, instead of

$(document).ready(function(){
 
$("#submit").click(function(){

  
...

  return 
false;
 
});
}); 

modify to

$(document).ready(function(){
 
$("#submit").click(function(){

  
...

 if(
hasError == false{
  
$(this).hide(); // Remove this submit button (to stop 'em re-submitting unitentioannaly)
  
return true// We are valid so hand back to default action
 
else {
  
return false// No good, let's try again
 
}
}
); 

Trevor

03.11.2009

@Willabee-
Maybe I’m missing your point here, but basically you are removing the AJAX portion of the form. Right?

If you take a look at the date of the post, it’s about a year and a half old, so yes, I have learned some things over time and would have done some things a little differently.

Willabee

03.11.2009

@Trevor-
Yes, because you don’t need it for this application to work.

Well done for getting almost everything right over a year ago.

Perhaps you should put an update that there are some security concerns and that you would do things differently having gained more experience.

That is what these tutorials are all about. I’m heavy into ASP.NET and Java MVC but I’m here to learn PHP and jQuery so I thank you for that.

Trevor

03.11.2009

@Willabee-
Oh the AJAX functionality is definitely not required for this form to work, but the whole point of the tutorial was to show how to use jQuery to create an AJAX form.

I have since created a similar article: WordPress & jQuery Contact Form without a Plugin

Willabee

03.11.2009

@Trevor-
That’s fine but read your commenter’s feedback, there is a lot of interest in the PHP mail() function. You just chose a bad example for Using jQuery to create an Ajax form.

For those who are concerned about the dangers of the application, assuming I have not already convinced you, take a look at http://www.phpbuilder.com/columns/ian_gilfillan20060412.php3 for the extra amount of security you might take with this sort of application (and the link example is using a hard-coded email address, which is much more secure than the open email address in this application).

paco

03.11.2009

Thanks for the post Willabee. I’ll be checking out that link you posted.

Thanks again Trevor. Have you turned to the darkside and started drinking coffee yet? Muhaha

vince

03.12.2009

Hello,

I had a quick question about forms sending phantom emails with no information. I have used your form as a template for a couple spots in the learn section of our site. When I have people test out the forms and submit we receive the information fine. However, every once in a while and at random times I’ll get one, two, three or four of the forms sending an e-mail to me at the exact same time with empty fields. I’m not sure what is causing this. I just want to make sure someone isn’t trying to send us info and it gets removed. Wasn’t sure if there is something (google crawl or bot, perhaps) triggering the form. Anyway, any help on this puzzle would be greatly appreciated. Thanks.

Trevor

03.12.2009

@vince-
Someone could be directly browsing to the php file that sends the email.

The easiest solution would be to check to make sure the required values are filled in before sending the email. So, change this:

mail($mailTo$subject$message"From: ".$mailFrom); 

To this:

if($subject !== '' && $mailFrom !== && etcetc{
 mail
($mailTo$subject$message"From: ".$mailFrom);

Obviously you will need to replace etc, etc with the rest of your required fields.

vince

03.12.2009

Thanks Trevor! I’ll try that…

vince

03.16.2009

@Trevor,

I made the changes you suggested but I still periodically receive empty emails. I receive emails with the appropriate subject line letting me know which form was submitted but the meassage fields are empty. It seems to be happening more often (I’m thinking because we are getting a little more traffic).

You mentioned in your comments that someon could be browsing to the php file directly…I was wondering how that happens.

Anyway, I’m at a loss. If someone is using an older browser or one that doesn’t handle php file well, could that cause any issues?

Trevor

03.16.2009

@vince-
Do you have the correct PHP validation as well? If you take a look at the JS file, you can see the URL where the PHP script is located, so someone could take that URL and browse to it. But, if you put in the conditional statements correctly so that it only sends the email if certain fields are set, that shouldn’t be a problem.

Which browser a user is using should not have any impact, since PHP is executed at the server level.

That is about all the suggestions I think I can give without looking at every single line of your code and addressing your specific needs.

Fernando

03.17.2009

@Trevor,
I’m finding your tutorial very useful! thanks a lot!. The only trouble I’m having is a very simple one: How would you code and validate a simple radio set, checkbox set and select combo box. The issue is I can’t figure out how to adquiere the superglobal GET for those items since i can’t create a temporary “value”. the value is already set.

Perhaps it is too of a newbie question, but I’m interested in coding and validating only with PHP a very accesible form like yours but with these additional entities.

Hope anyone can help!

Trevor

03.17.2009

@Fernando-
There have been some other comments that should help you in figuring out how validate radio buttons and select boxes.

Also, you can take a look at some of my other recent posts: [url=“http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/” rel=“nofollow”]
WordPress & jQuery Contact Form without a Plugin[/url] and [url=“http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/” rel=“nofollow”]
Flexible and Semantic Forms with a Little jQuery[/url] for some more info.

Hopefully that should help to answer some of your questions.

Fernando

03.17.2009

That was very helpful!! If only you could point me in the right direction about validating select boxes with PHP, cause neither of the example forms have any of this kind!

Thanks for every answer!

Trevor

03.17.2009

@Fernando-
You would validate a select just the same as you would a normal input.

Leave the first option with an empty value:

<select name="dropDownName" id="dropDownName">
 <
option value="">&nbsp;</option>
 <
option value="1">1</option>
 <
option value="2">2</option>
</
select

Then, just check to see if it is empty on the PHP side:

if(trim($_POST['dropDownName']) === ''{
 
echo 'Empty';

Selena

03.19.2009

Hi Trevor, brilliant tutorial and comments. Taking this one or two steps further, I have a webpage with multiple form caluclus and submits, on every submit the other form resets, which I don’t want. Upon searching the net I found that AJAX will do this for me but don’t know how…

Calculate My Commission

<form method "POST" action="">

Total P.E. <input type="text" name="premierEnergy" value="" size="2"/> 
Total E.F. <input type="text" name="energyFirst" value="" size="2"/> <?php echo "(<b>".number_format($EFPercentage,0)."%)</b> ";?>
Total P
.A. <input type="text" name="payAs" value="" size="2"/> <?php echo "(<b>".number_format($PAPercentage,0)."%)</b> ";?> 

There are 4 other divs with similar codes (different calculations). No error validation is needed.
Been trying to find the answer for 5 days now and I’m pulling my hair out!!!

Trevor

03.19.2009

@Selena-
I’m not clear on what you are asking. So are you saying that you have multiple forms on a page that you want to separately submit with AJAX?

Selena

03.19.2009

Thanks for getting back…Yes I want to submit separately and NO refresh to keep the users input and results on each form…
Here’s the page where it all is… 
www.dorsetwebdesigns.co.uk/bg/test.php

Many Many Thanks

Trevor

03.19.2009

@Selena-
I would probably start by adding a class to each of the forms. Then, using jQuery, when those forms are submitted, serialize the form data, then submit it via an AJAX request to the action attribute of the form.

It would probably be easier to start from scratch rather than modifying the existing jQuery.

sander

03.23.2009

Thanks a lot for this explanation. I don’t know what newbies webdevelopers like me would do without willing teachers like you.

Chris

04.02.2009

Great form Trevor! I put it to use on my ‘Contact Me’ area on my site at www.idea-palette.com. I can’t figure out how to remove the numbers next to the form fields. Can you help me?

Trevor

04.02.2009

@Chris-
Try this:

ol.forms { list-stylenone

Chris

04.02.2009

oh, ofcourse. duh! I use the ordered list so seldomly I forgot that it adds numbers. Thanks for the help! Great Form!

Wendy

04.08.2009

For some reason, the contact form won’t send the message to the specified email in sendemail.php
It does everything ie. the required fields, the success message.
It just won’t sent the message to the email

Trevor

04.08.2009

@Wendy-
Does it work without JavaScript? When JavaScript is enabled, do you see any error messages in the Firebug console? Do you have a link?

Wendy

04.09.2009

@Trevor-
Ah nevermind I forgot to add the javascript. But I was also wondering is there a way for the ‘Name’ field to show up in the email so that I know who it is from?
I know that there is a field there in the form, but it doesn’t actually send the name along with the email

Wendy

04.09.2009

and also how do I add extra message fields, select boxes and radio buttons? I am an absolute noob so I have no idea. I tried understanding the other comments about select boxes but I don’t get it.

Trevor

04.09.2009

@Wendy-
Basically, you will need to add a new field to the form. So let’s say telephone

<input type="text" name="telephone" id="telephone" /> 

Then, add in the validation:

var telephoneVal = $("#telephone").val();
if(
subjectVal == ''{
 
$("#telephone").after('<span class="error">You forgot to enter the telephone number.</span>');
 
hasError true;

Next, pass in the new telephone value, or serialize the form fields:

{ emailToemailToValemailFromemailFromValsubjectsubjectValmessagemessageVal, <strong>telephonetelephoneVal</strong}

Then, you will want to add in the validation in the verify.php as well, and in sendMail.php is where you would adjust the email text:

$telephone $_POST['telephone'];
$message $_POST['message'];
$body 'Telephone: ' $telephone "n" 'Message: ' $message;
   
mail($mailTo$subject$body"From: ".$mailFrom); 

I have also written a couple of other tutorials about forms/ajax/jQuery that may be helpful:

<ul>
<li>WordPress & jQuery Contact Form without a Plugin</li>
<li>Flexible and Semantic Forms with a Little jQuery</li>
</ul>

webguy262

04.12.2009

I’m trying to use jquery to grab the value generated by an an ajax call (done in form 1) and then assign that ajax-generated value to a field in another form (form2).

You can see the page and view the source here:
http://www.eastexhaust.com/inventory_.php

I’m using the “click” function and attaching it to the form 1 submit button. 

If I hard code the value I want like this…

$(document).ready(function() {
  
$("#partnumber").click(function(){
  
$('#partnum').val 'this works' );
 
});
 
}); 


... jquery assigns it to the field.

But if I code it to assign the ajax-generated value…

$(document).ready(function() {
  
$("#partnumber").click(function(){
  
$('#partnum').val ( $('#myspan').text() );
 
});
 
}); 


...it does not work.

Could one of the problems be that the ajax-generated value is not available when the code fires? The same submit button is triggering both the ajax request and the jquery function.

Any sugeestions?

Trevor

04.13.2009

@webguy262-
Did you figure out what was going on? It seems to work for me. When I make selections in all of the select elements, then click on Get my part number, it populates the Your Part Number is input field.

webguy262

04.14.2009

Sorry, that part works.  The problem, tho, is getting the part number to populate the field in the lower form.  It should appear in the “Part Number:” field as well as in the “Your Part Number is” field.

If you go to this version of the page…
http://www.eastexhaust.com/inventory_1.php
...and use FFox, you’ll see how it should work.  But of course, that version fails in IE.

I developed everything w/o jquery as it is new to me.  I only turned to jquery in an effort to solve the IE problem.

Can you see how to fix it, using jquery or not?

I would be VERY grateful for any advice as this is driving me nuts!

Trevor

04.17.2009

@webguy262-
Right off the bat, it looks like there is an error in your JS:

Error: $ is not defined
Source File: http://www.eastexhaust.com/inventory_1.php
Line: 195

webguy262

04.17.2009

@Trevor-

My line numbers (bbedit) are not matching up with whatever you are using to see the error. What are you viewing the page with when you see an error in line 95?

Trevor

04.17.2009

@webguy262-
I saw the error in Firebug

ExploreMyBlog

04.19.2009

Great I love such things for my websites, and it works fine with me in both IE and Firefox.

webguy262

04.19.2009

Sorry, the error you saw was because I inadvertantly left in a jquery call but did not have have the library referenced.

Try http://www.eastexhaust.com/inventory_1.php again in FF and you’ll see how the form should work. 

Trying to get it to work that way in IE

Trevor

04.20.2009

@webguy262-
Not sure what to tell you here. It doesn’t even appear that you are using jQuery anymore.

sergi

04.21.2009

hi, trevor,

i’m amazed at how you respond to everybody’s comments.  quickly, too.  that’s awesome of you.  it’s also great to see how many people have tackled your tutorial and commented on it.

some difficulties i ran into while working my way through this tutorial are as follows (note: i’m new to ajax, and a novice with both js and php):

- the sendEmail.php linked to at the bottom of the article is referred to as “sendemail.php” in your code.  capitalization caused conflicts.

- it took me some time to find the loading gif, too

- i had to realize that the form action ‘post’ referred to “itself” (index.php, in my case)

lastly, logging in and/or registering was tough.  it seemed for a moment that i could log in using my facebook account.  or my Wordpress.com account. but those didn’t work.

only mentioning these things because i figured you’d appreciate hearing them.

best,

sergi

Trevor

04.22.2009

@sergi-
Thanks so much for adding the comments.

Regarding the capitalization of sendMail.php, unfortunately when I uploaded it via WordPress, it made all the letters lowercase. I didn’t notice any problems with it though, so I guess it depends on the server.

I’m not sure what you mean by having trouble logging in. Where were you trying to login?

sergi

04.22.2009

@Trevor-
i realize what the confusion was re: login.  i clicked on the link in the “speak your mind” section that says “log in”.  whereas i should have click on “register”.  on the “log in” page, it looked like i could log in with my google, fb, etc.  but now i realize that one cannot log in via those methods unless they first register with trevor davis.com.  i was rushed.  it may be a ui thing; maybe not though.

i agree with your love of wordpress.  it’s the bomb.

Matt

04.24.2009

Thanks for the code, it works brilliantly!

I have one question. Rather than have the form slide up on submit I have it fade out (this fits in better with how the rest of my site works). I’ve managed this without any problems simply by changing ‘slideUp’ to ‘fadeTo’ in the javascript code. However, when the mouse moves over the ‘faded out’ form elements it registers that they’re still they and changes to a pointer or text select cursor.

Whilst this isn’t a major problem, it does look a bit weird seeing the mouse cursor change as it seemingly moves over nothing.

Is there any way to have the form removed completely once it’s been submitted, rather than moved out of the way or faded out?

Thanks :)

Trevor

04.24.2009

@Matt-
Sure, just use the remove() function.

Matt

04.24.2009

Fantastic, works like a charm! Many thanks.

العاب

05.01.2009

thanks it’s very useful for me thank you

Fred

05.11.2009

Hi Trevor,
Thank you for sharing your work.
I have been trying to integrate this form on a friends website without success since I am not a professional and just learning php and forms and such…

In the form action=”/play/jqueryAjaxForm/” what does that refer to? Do I have to change it to something else?

Also I tried to modify the form with:
ToFredJason<?php if(isset($emailToError)) echo ‘’.$emailToError.’‘; ?>

Instead of:

To<input type=“text” name=“emailTo” id=“emailTo” value=”” /><?php if(isset($emailToError)) echo ‘’.$emailToError.’‘; ?>


For the visitor to choose which email address to send the message to.  Works great on FF but nothing visible on IE…?

Could you help with those issues?

Thank you,

Fred

Trevor

05.11.2009

@Fred-
Can you provide us a link to your form?

Trevor

05.11.2009

@Fred-
I actually don’t see anything in FF. I see a completely blank page. It looks like your script tag is not closed.

Fred

05.11.2009

Yes,  wasn’t closed…
Sorry!
Fred

Trevor

05.11.2009

@Fred-

A couple of things:
<ol>
<li>It looks like jQuery is not referenced correctly; I don’t see the jQuery library when I go here.</li>
<li>The form action should be the page itself: index.php</li>
</ol>

That should get you going. Good luck.

Fred

05.11.2009

@Trevor-
Does that mean that in the form the action=”/play/jqueryAjaxForm/” should be replaced with action=“index.php”?

Trevor

05.11.2009

@Fred-
Yes

Fred

05.12.2009

@Trevor-
Thank you very much,
Your code is great!

Brett

05.12.2009

Has anyone made this work with ColdFusion? I have everything working except the ability to include the message within my tag. If I remove the message variable, the e-mail is sent.

Doesn’t work:
#EMAILCOMMENTS#

Works:
<code></code>

Brett

05.12.2009

Nevermind. I had a mispelled vairable.

@Trevor
Thanks for the great code. I’m using it with thickbox 3.1.

Trevor

05.12.2009

@Brett-
Nice!

Got a link to share your work?

Brett

05.12.2009

@Trevor -

Sure. Go to http://www.internationalpoultryexposition.com/exhlist/exhsearch.cfm and type scissors in the product/keyword field. The “Report offensive search terms here!” link uses your code, thickbox and Coldfusion.

Trevor

05.12.2009

@Brett-
Nice job, looks great!

Brett

05.12.2009

@Trevor-

Thanks. I’m not a designer as you can tell. I like the backend. Making stuff work ya know?

Here’s my idea of design: www.pierangler.com

Yeah, that’s my homepage. Simple and say’s it all. Simplicity at it’s finest!  Personally I think it’s the greatest Web page in the whole world but what do I know. [I hope you all laughed just a little!]

Matt

05.13.2009

Love the script. Took a bit of thought to get it working in my particular setup, but once I’d figured it out it was perfect.

For what it’s worth here’s where I’m using it:

Ashville Inc - http://tinyurl.com/pmh9fo

Go to the contact page and click on the ‘Request more information page’ link :)

Trevor

05.13.2009

@Matt-
Nice, great to see modified working examples!

Sanam Maharjan

05.18.2009

Hello Trevor
Error: hasError is not defined
Source File: http://localhost/sanam/email/ajax.js
Line: 44

Could not solve this error. Help Me Please

Trevor

05.18.2009

@Sanam Maharjan-
Did you modify your JavaScript at all? That error means that the variable isn’t being defined anywhere in your code.

In my example, I define this at the top:

var hasError false

Pete

05.20.2009

Hi Trevor,

I’ve just tried testing your scripts. It all seems to work fine and gives the response ‘Your email was sent’ but I don’t ever receive the email that was sent.

I’ve changed the form action to index.php, the page itself.

Any ideas?

Cheers.

Trevor

05.20.2009

@Pete-
Do you have Firebug installed? What response do you see in the console?

Is PHP mail setup correctly on your server?

Do you have a link to your form?

Pete

05.20.2009

Aghhhhh! Sorry, I was being a total twit.

I wont even embarrass myself at explaining what I did.

Cheers very much for the script and sorry to waste your time there.

Carlo

05.23.2009

I was looking for a script like this one!
This is perfect! Congrats!! Thank you so much!!!

Only a question: “What’s for the exit() function at the end of thanks.php file?”

Thanks, again.

Carlo

05.24.2009

@Carlo-

I understood: it’s because is the final part of the “if” function. Thanks 4 all!!

Sandeep

05.29.2009

@Trevor-
Absolutely right

hakim

06.01.2009

Firstly, thanks for a super script!

I do however have a slight problem with adding additional fields to the form and actually having the data appearing in the body of the mail.  Could anybody give me a hint as to what I’m getting wrong here?
<code></code>

Ta

hakim

06.01.2009

something went wrong here (code snippet got lost).

Problem is in here:

Firstly, thanks for a super script!

I do however have a slight problem with adding additional fields to the form and actually having the data appearing in the body of the mail.  Could anybody give me a hint as to what I’m getting wrong here?

$mailFrom $_POST['emailFrom'];
$subject stripslashes (utf8_decode ($_POST['subject']));
$message stripslashes (utf8_decode ($_POST['message']));
$name stripslashes (utf8_decode ($_POST['name']));
$company stripslashes (utf8_decode ($_POST['company']));
$body 'name: ' $name "n" 'company: ' $company "n"  'Message: ' $message;

mail('info@example.com'$subject$message"From: ".$mailFrom); 

Ta

Trevor

06.01.2009

@hakim-
You want to pass in the $body variable instead of the $message variable into the mail function.

hakim

06.02.2009

@Trevor-
Thanks Trevor
Still I must be doing something wrong as it isn’t working.

There seem to be a problem with this line: mail(‘info@example.com’, $subject, $message, “From: “.$mailFrom);

If I take it out, mail comes through - I leave it in and no mail arrives.

I’m not a developer, and I am desperately trying to understand how this work, but clearly I’m having problems with the php unless it’s spelled out.

hakim

06.02.2009

@Trevor-

Please disregard my last post, apparently I’d made a syntax error in line $body = ‘name: ’ . $name . “n” ‘company: ’ . $company . “n”  ‘Message: ’ . $message;

added a . after the “n” and that fixed the problem.

Thanks again for you help ;-)

Jeff

06.25.2009

Nice article, I was looking for how to make ajax calls using the jQuery library (I was one of the people making 2 functions everytime I needed to retrieve data using an ajax call, and I found out the jQuery lib can save me a lot of time), thanks again for the info on how to do it.

iwanttobelieve

07.02.2009

Very nice script ;)

Sanam Maharjan

07.03.2009

Hello Trevor,
   

  $(”.addressDiv span”).live(“mouseover”, function(){
  //clickable function here…...
  ————————————
  });


I have used the above live() event to trigger the function on mouseover in the dynamically added elements. But the problem i got is that once the live event is called it takes the class of the element and stores. And when the class of that particular element is changed dynamically the live() event does not detect the new class added dynamically, instead it takes the former class. Live() event does not update the class.  How can I solve this problem?

Jesse

07.14.2009

Man thats a great tutorial thanks a lot. I am trying to figure out how one could simplify the process of validating via JQuery and PHP.

I think it would be much easier if PHP checked for errors, and returned it to JQuery thus keeping the code at a minimal on the front-end.

Trevor

07.15.2009

@Jesse-
Sure, you could definitely do something like that. There are many options that you can find online, or you could easily build it yourself.

Brett

07.23.2009

Awesome tutorial, I added some extra fields and adding it to a wordpress theme that I’m currently developing. Thanks alot!

Harshit

07.28.2009

Hi Trevor,

Firstly, thank you for this awesome tutorial.

I am a novice designer and new to forms. Could you please help me with it?

I have added the form on http://harshitdave.com and it works fine, however it does not send the email. I am trying to send the email to .(JavaScript must be enabled to view this email address). I get the message saying mail sent successfully however, I do not receive the email.

I am pretty sure I am using a incorrect path reference or something. Could you please help??

Below is the form code on my index.html page

     
     
 
  * All fields are required
 
  Your eMail address

  Subject

  Message
  Send Email »
 

Harshit

07.28.2009

Sorry for the code in the previous comment - I think the HTML code didn’t appear.
Hi Trevor,

Firstly, thank you for this awesome tutorial.

I am a novice designer and new to forms. Could you please help me with it?

I have added the form on http://harshitdave.com and it works fine, however it does not send the email. I am trying to send the email to .(JavaScript must be enabled to view this email address). I get the message saying mail sent successfully however, I do not receive the email.

I am pretty sure I am using a incorrect path reference or something. Could you please help??

Trevor

07.28.2009

@Harshit-
Everything looks good on the JavaScript errors, and I didn’t get an error. Does it work without JavaScript enabled? I would read through some of the previous comments and maybe that will help.

Harshit

07.28.2009

@Trevor-

Hi Trevor,

Thank you for the reply. Yes, there are no errors. However, I do not receive an email when I fill the form and submit. I want the email to be sent to .(JavaScript must be enabled to view this email address).

Where should i set the emailToVal to .(JavaScript must be enabled to view this email address). Sorry if this sounds stupid - I am not that good with php and javascript

Please help!

Thank you.

Trevor

07.28.2009

@Harshit-
In the sendEmail.php file, you want to set $mailTo = .(JavaScript must be enabled to view this email address). Remember, this was not designed to be a contact form, just an email form. But people previously in the comments have discussed how to change it into an email form.

Harshit

07.28.2009

@Trevor-

Thank you again Trevor.

I was reading the comments above and I think I should be able to change it.

Just one question though, does the action in form have to point to the sendEmail.php file?

This is what I have at the moment -
form action=”/” method=“post” id=“sendEmail”

Harshit

07.28.2009

Hi Trevor,

Ignore the previous message. It works now.

Another questions - How do I display the success message on the same form? I mean I want people to be able to send more than one message without having to refresh the page.

Trevor

07.28.2009

@Harshit-
Just modify the JavaScript so that the form no longer slides up. This is the code to edit:

$("#sendEmail").slideUp("normal", function() 

Colin

07.31.2009

Trevor this is awesome.

I’m a total retard at code… meaning I taught myself and I try to learn new things, but I blow it alot. When I first started on this I was like oh shit this is going to suck, but after tweaking out with it for about… 6 hours now, I finally got it working somewhat decent.

Thank you for this script. I’m loving JQuery more and more every day.

Here’s what I’m using it on: http://fiftyonestudios.com/projects/web/lavenderlounge/contact/
Please don’t laugh @ that project it’s super “under construction”.

Do you have any recommendations for how to code in html for the email output that I can add to the sendemail.php? So far I’ve only gotten as far as getting line breaks working via “n”. Thanks for any pointers.

Oh before I totally forget, one thing I noticed about your provided JS file is that it’s linking via wordpress paths. It threw me at first until I noticed.

Thanks again. Now, on to reading http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/ and http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/.

Trevor

07.31.2009

@Colin-
I’m glad you are finding the script useful.

In order to send html using PHP mail, you will need to send the appropriate header. If you review the documentation on the PHP mail function, you will find more examples. Good luck.

manuel

08.01.2009

Hi Trevor,

you’re script looks like the thing I’ve been looking for! Thanks!

But there’s a little problem I couldn’t solve so far:

I try to display the form within a lightbox (jquery facebox) by putting the code in a external document and loading it via facebox, which works fine.

But when I hit the submit button, the whole page is relaoding and the error- or success-message shows the external document itself instead within the lightbox! When I try the document wihout the lightbox, it works fine!

Is there anything I can do to make sure, the messages are displayd within the lightbox without reloading the whole page?

Thanks!

Manuel

Trevor

08.01.2009

@manuel-
Can you provide a link to the page?

manuel

08.02.2009

@Trevor-

Hi Trevor,

thanks for asking. I uploaded the scripts here:

http://netzding.ch/contact_test/lightbox.php
this is the demo with the lightbox. Just hit the “Click here for the lightbox” button to see it.

and here’s the form script, I call when displaying the lightbox:
http://netzding.ch/contact_test/light_index.php

As you can see, when I test the form outside the lightbox (just the light_index.php), it works perfectly, but when I do the same in the facebox-plugin, the whole page is relaoding and the error- or success-message are displayed in the external document instead within the lightbox.

In the folder, the following documents are present:

- light_index.php (your form I call in the lightbox)
- lightbox.php (the document I call the lightbox)
- sendmail.php
- submitform.js
- thanks.php
- verify.php

- facebox.js
- jquery.js
- and the css scripts

If you see anything I could change to make it work, please tell me, otherwise I can do the whole thing without the lightbox! Thanks again!

manuel

Trevor

08.03.2009

@manuel-
Ok, so basically what is happening is, you load the regular page, then you click the lightbox link, and it pulls in the lightbox. This is where you need to bind the form validation function to the submit button. Or, you could just open the lightbox in an iframe, either will work.

Nick Iredale

08.09.2009

Just testing out the form - looking good except for one small problem that I don’t know how to fix.
With JS turned off in the browser I can send emails with a line break in (CR), but with it turned off my system is reporting that the php mail() function doesn’t like the line endings - they need to be rn, not just n
php is obviously doing this right but JS isn’t.  As I am pretty ignorant of JS I’m not sure how to fix this.

Trevor

08.10.2009

@Nick Iredale-
Not sure what it could be. It’s still using PHP to send the emails, regardless of whether JS is enabled or not.

games

08.13.2009

thank you it’s useful and cool

ghprod

08.14.2009

Hi ... can u give us an example how to do update div like prototype in jQuery ... so when we make a comment, then the entry will show in comment list .

regards

Trevor

08.15.2009

@ghprod-
Maybe I’ll have to do that for another tutorial. Thanks for the suggestion!

Web Suunnittelu

08.26.2009

I have been using some messy code which served the same purpose but this can do it much more smoothly and its lighter;  very valuable code, thanks for posting ;)

Andres

09.12.2009

several months looking for this, tks .

works great

Colin

09.23.2009

Back again…

Trevor, I was wondering if there is a way to reload the form without reloading the page. So, basically, you fill out the form, submit, it loads the success message and then below that there is a link to reload the form. On first thought, it would seem possible to have some sort of onclick function added to the link to tell it to remove the success message and reload the form, but I have no clue as to how to make this possible (js noob).

Thanks for any insight.

Trevor

09.23.2009

@Colin-
Sure, it’s definitely something you can do. When you append the success message, append a link to reload the form as well. Then attach a click event to that link, that will remove the success message and clear the form fields when clicked.

Colin

09.23.2009

on second thought… is there a way to have the success message clear itself after a few seconds and automatically reload the form?

That seems like an ideal scenario. Could you give a code example that might work that I could toy around with?

Colin

09.23.2009

@Colin-
Note to self… need to learn jQuery properly before trying to modify code.

Trevor

09.24.2009

@Colin-
Sure, you could use setTimeout to set a specific amount of time before you remove the success message.

Florian

10.06.2009

Thank you very much for this great tutorial and form.  I am using it for a project and it works great. One issue came up for me.

1.)  When I receive the email in outlook or gmail, the ’ and ” signs get converted into characters. I used the following code from an earlier post.

$message stripslashes (utf8_decode ($_POST['message'])); 

When I use that code, the ’ signs get converted into a ? sign. Also the encoding for the email still says “western europen ISO” in outlook.

Is there a way to control this better?

2.) Is it possible to have two of these forms on the same page? Would I have to rename all ID’s or can I just copy the form and use two on one page?

thank you,
kindly
Florian

Trevor

10.06.2009

@Florian-
1) Did you try just using stripslashes without the uft8_decode? You can also try passing additional headers in the mail function.

2) You would have to change all the IDs. You could easily modify it so you wouldn’t have to do that, like I did in this article.

Johnny

10.09.2009

Just wanted to write and say thanks for the great jQuery tutorial. It help me complete our Bay County Landscaping website contact us form. And without the need to refresh we have had a lot of clients asking us how we did it and we have been send them to this link. So thanks for making our Panama City Landscaping website better and much more user friendly.

Jason

10.10.2009

Trevor, I know everyone else has said the same thing, but thanks for this tutorial.  It’s exactly what I’ve been looking for.  Once I get my client’s site up and running, I’ll post a link for you. 

I’ve been using your examples to make my own code and I have a question.  What if I have form data that I didn’t validate, therefore didn’t assign a JS variable to(such as a list box)... how would I pass that info in the $.post function to my php script?  Do I have to go ahead and assign a JS variable to that form data first? 

Thanks for the help!

Jason

Trevor

10.11.2009

@Jason-
Take a look at the serialize() function.

Jason

10.11.2009

@Trevor -
Oh man, I missed that… that’s perfect, thanks!

Francesco

10.20.2009

Trevor,
could you please explain me how to ad input fields that don’t need validation? I heard you talk about serialize on one of the comments above. But I don’t get it, how to implement this serialize in your otherwise great solution.

Trevor

10.20.2009

@Francesco-
The simplest method is to change this in the script:

{ emailToemailToValemailFromemailFromValsubjectsubjectValmessagemessageVal } 

And use serialize to get all the form fields:

var formFields = $('#idOfFormHere').serialize(); 

Then, you have all of the data from the form, so you can replace the first line I mentioned with the new data:

{ formFields } 

Francesco

10.20.2009

@Trevor-
Thank you for your fast reply. I’m gone dig in to it right away.

Paul

10.20.2009

Great code, but…

I’ve got a suggestion; rather than using several if statements to validate the fields - I’d replace it by a a single function taking fieldID and errorMessageFieldID as parameters.

try following:

function validateLengh(field,error_class)
    
  
if(field.val().length 1){

   field
.addClass(error_class);
   return 
false;
   
  
}
  
  
else {
   
   field
.removeClass(error_class);
   return 
true;
   
  
}
   

Paul

10.20.2009

above code adds an error class to a field ie changes its background colour to red; it’s a bit different approach.

you may also replace error_class parameter by a html element id where you want an error message to appear…

Trevor

10.20.2009

@Paul-
Absolutely there are different ways to implement this kind of thing. If you take a look at the date on this article, you will see that it is over 2 years old.

If you take a look at some of my more recent articles:
[url=“http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/” rel=“nofollow”]
WordPress & jQuery Contact Form without a Plugin[/url] and Flexible and Semantic Forms with a Little jQuery, you will find different approaches to validation.

As far as just adding a class to the form field, I don’t think that is enough from a user experience point of view. What if you have someone that is color blind? It’s so much clearer to put the text there identifying the problems.

Amir

10.23.2009

Thank you for putting this together, so helpful and easily scalable.

Dean H

10.27.2009

Great form.

Really looking at adding radio button validation.  How can I make that happen???

Please help!!!

Trevor

10.27.2009

@Dean H-
Take a look at some of the previous comments, this question has been addressed.

العاب بنات

11.01.2009

Thanks for this script and the tutorial, I have the script on two sites and there are no errors.

David

11.04.2009

Hi Trevor,

Thanks for this script - works a treat! I’m using it within a JQuery Modal pop-up for a contact me section on a site, and I have one quick question:

Once the user fills out the form and sends it off, he’s presented with the section telling him it’s a success. I’m trying to add a ‘close’ button on the end of this but it doesn’t seem to be working - was wondering if you could take a look and see if you spot anything missing?

$(document).ready(function()
 
$("#submit").click(function(){               
  
$(".error").hide();
  var 
hasError false;
  var 
emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
  
  var 
Name = $("#name").val();
    if(
Name == ''{
   
$("#subject").after('You forgot to enter your name.');
   
hasError true;
  
}
  
  
var Email_address = $("#emailaddr").val();
  if(
Email_address == ''{
   
$("#emailaddr").after('You forgot to enter your email address');
   
hasError true;
  
else if(!emailReg.test(Email_address)) 
   
$("#emailaddr").after('   Enter a valid email address please.');
   
hasError true;
  
}
  
  
var subjectVal = $("#subject").val();
  if(
subjectVal == ''{
   
$("#subject").after('You forgot to enter the subject.');
   
hasError true;
  
}
  
  
var messageVal = $("#message").val();
  if(
messageVal == ''{
   
$("#message").after('You forgot to enter the message.');
   
hasError true;
  
}
  
  
  
if(hasError == false{
   
$(this).hide();
   $(
"#sendEmail li.buttons").append('');
   
   $.
post("emailer.asp",
       
{ NameNameEmail_addressEmail_addressSubjectsubjectValMessagemessageVal },
        function(
data){
      
$("#contact").slideUp("normal", function() {       
       
       
$("#contact").before('SuccessYour email was sent. Close ');           
      
});
        
}
     
);
  
}
  
  
return false;
 
});         
}); 


Thanks in advance!
David

David

11.04.2009

hmmm, weird, it left off the last part:

$.post("emailer.asp",
       
{ NameNameEmail_addressEmail_addressSubjectsubjectValMessagemessageVal },
        function(
data){
      
$("#contact").slideUp("normal", function() {       
       
       
$("#contact").before('SuccessYour email was sent. Close '); 

Trevor

11.04.2009

@David-
You need to bind an event to that close button to remove the modal window when clicked.

Jill

11.12.2009

Hi Trevor, I was wondering if there was a way to tweak the form to send out more than one email with one submit click, like send to a friend and 2 other friends at the same time.

thanks

Trevor

11.12.2009

@Jill-
You can change the regular expression that validates the emailTo field on the JS side and the PHP side so that it allows comma separated email addresses.

There are tons of regular expression libraries out there that should get you what you need.

Jill

11.12.2009

@Trevor-
Thanks but the design calls for 4 input boxes for email addresses and not just one textbox.
other thoughts?

Trevor

11.12.2009

@Jill-
Sure, just concatenate the data from those 4 fields and pass it in as the to parameter in the mail function.

Dan

11.18.2009

Whats the difference from the Jquery form plugin?

Trevor

11.18.2009

@Dan-
It all depends on what you are looking for. If you are only going to have one form on your entire site, it’s probably easier to write custom jQuery like I’ve done, and the file size is only about 1k.

But if you are going to have a ton of forms and need the additional functionality, then the jQuery Form plugin may be the better option at a file size of 19k.

Frederik

11.24.2009

Thanks for this nice tutorial but I have the following problem:

Amavis (server antivirus system) adds this in the header:

X-Amavis-Alert: BAD HEADER Non-encoded 8-bit data (char E4 hex) in message header ‘Subject’: Subject: Blog-Kontaktanfrage: 344366374337 test as welln”

when I use umlauts in the subject like “äöüß test as well”.

Another problem is that the name (here “äöüßtest”) of the sender is not displayed correctly when there are umlauts in it and the message is not displayed in a new line:

Von: äöüßtest
Nachricht: rnäöäüpß00

contact_send.inc.php:

<code></code>

Thanks for help

Frederik

11.24.2009

The code feature didn’t work so here again my modified contact_send.inc.php:

Frederik

11.24.2009

Sorry, last try:

$name stripslashes (utf8_decode ($_POST['name']));
$mailFrom $_POST['emailFrom'];
$subject 'Blog-Kontaktanfrage: ' stripslashes (utf8_decode ($_POST['subject']));
$message stripslashes (utf8_decode ($_POST['message']));
$body nl2br('<strong>Von: </strong>' $name "rn" '<strong>Nachricht:</strong>' "rnrn" $message);
// To send HTML mail, the Content-type header must be set
$headers  'MIME-Version: 1.0' "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' "rn";
$headers .= "From: " $mailFrom "rn";
mail('my@email.com'$subject$body$headers); 

It works now with the JavaScript solution but not without JavaScript. With JavaScript enabled I only have the warning message from Amavis. With JavaScript disabled I have all the problems from above because the headers are not added etc.

Len Ocin

11.24.2009

@Frederik-
Maybe you can replace charset=iso-8859-1 with charset=utf-8 (top of my head, pls check)?
Seeing I work with all kind of languages I always use unicode…works for me.

Frederik

11.25.2009

As I said: It works already with JavaScript but only with those errors above when I use the PHP version. So the problem is not the encoding but that the headers are not sent like in the JavaScript version and I would like to know why.

Len Ocin

11.25.2009

[EDIT] Comment deleted per commenter’s request.

Limco

12.05.2009

Thanks anyway.Is it working with jquery 1.2.3?
I got downloaded this PHP-AJAX and I found out it is using Jquery 1.3.2
http://www.phpstring.co.cc/phpclasses/modules/ajax-registration-module/register/

It is very nice but my apps is using lower version of Jquery

Johan Falk

12.14.2009

Nice blogg this is the third time i read it and i just gotta say that you have a point in your blogposts! keep the good work up!

indialike

12.16.2009

Very nice and useful tutorials to web designers,
Thanks for posting.

Macedonia

12.28.2009

I was looking for something like this :)
I think I will use this solution on my web site. I can see here that it uses jquery 1.3.2 version. Will this work on 1.2.6 ?

Trevor

12.28.2009

@Macedonia-
Not sure, it should. Give it a try.

zur4ik

01.03.2010

very usefull tool for easy posting with jquery. :)

Matt

01.09.2010

Great script, super simple and functions quite nicely. Thanks for sharing!

I have only one question. How would you slide the form back in after the info is submitted after say 5000ms? I’m very new to jQuery and javascript and have, but am learning as I implement, so please excuse me.

Here’s what I’m working with:  http://matthewnolting.com/portfolio.html#7

Trevor

01.09.2010

@Matt-
Glad you enjoy the script.

You could use setTimeout() to execute the fadeIn() function after some amount of time.

Matt

01.09.2010

Alrighty, in testing I was able to get setTimeOut() to work, but not with the fadeIn() function. Any ideas?

Thanks again

if(hasError == false{
 
$(this).hide();
 $(
"#sendEmail li.buttons").append('');
 
 $.
post("bin/sendEmail.php",
   
{ emailFromemailFromValsubjectsubjectValmessagemessageVal },
    function(
data){
    
$("#sendEmail").slideUp("normal", function() {       
     
     
$("#sendEmail").before('SuccessThanks! I'll be in contact soon.');           
     setTimeout("location.href = '
index.php;",1500);
    });
    }
   );

Trevor

01.09.2010

@Matt-
I’m not exactly clear what you are trying to do here. Why are you changing location.href? Don’t you want to call the fadeIn() function here?

Matt

01.10.2010

I was testing setTimeOut(). I DO want to use use the fadeIn() function, but not sure what to pass in or the syntax. Again, baby steps; my apologies.

Trevor

01.10.2010

@Trevor-
You can do anything in setTimeout(). For example:

setTimeout(function() {
 alert
('do something');
}1000); 

Matt

01.10.2010

I got it to function as I wanted, although I must admit it’s a bit sloppy. Thanks for your help!

if(hasError == false{
 
$(this).hide();
 $(
"#sendEmail li.buttons").append('');
   
 $.
post("bin/sendEmail.php",
     
{ emailFromemailFromValsubjectsubjectValmessagemessageVal },
      function(
data){
    
$("#sendEmail").slideUp("normal", function() {       
    
$("img#loading").remove();
    $(
"#sendEmail").before('Thanks, your email was sent!');
    
setTimeout(function() {
     
$("p").fadeOut(100);
    
}2000);
       
   
});
     
}
 
);
 
setTimeout(function() {
  
$("#sendEmail").fadeIn(200);
  $(
"#submit").show();
 
}3300);    

Vix

01.16.2010

hey.. what is this “/play/jqueryAjaxForm/ “??

can u give me the complete project??

thankx in advance

Trevor

01.16.2010

@Vix-
You can download the files at the bottom of the post.

Vix

01.16.2010

yeah i did..

but wots that ” /play/jqueryAjaxForm/”  wots in their???

and where is that “analytics.php”

Trevor

01.16.2010

@Vix-
/play/jqueryAjaxForm/ is the url to demo form.

analytics.php was just tracking code that I wanted to add to the page. You can ignore it.

francois

01.28.2010

Hello trevor,

I managed to get the form working last time but now i’m working on a new one and I am in trouble again.
I have fields that need to be validated some that don’t need validation and some checkboxes.
So this is my code I have so far for the .js script.

(...)
var 
telVal = $("#tel").val();
                if(
telVal == ''{
                        
$("#tel").after('blabla.');
                        
hasError true;
                
}

                
var emailVal = $("#email").val();
                if(
emailVal == ''{
                        
$("#email").after('gblabla.');
                        
hasError true;
                
}

                
var checkbox = $('#checkbox').serialize();

              var 
messageVal = $("#message").val();

                if(
hasError == false{
                        
$(this).hide();
                        $(
"#sendEmail li.buttons").append('');

                        $.
post("http://www.domain.com/sendmail.php",
                                
{ namenameValsurnamesurnameValstreetstreetValzipzipValcitycityValteltelValemailemailValmessagemessageValcheckbox},
                                       function(
data){
                                                
$("#sendEmail").slideUp("normal", function() {

                                                        
$("#sendEmail").before('thank you bit</a>');
                                                
});
                                        
}
                                 
);
                
}

                
return false;
        
});
}); 

My mail is delived as requested but the end page is my sendemail.php instead of the nice looking ajax effect with the loading in the same page as the contact form. Now my question is where do I go wrong in parsing the values of the checkboxes to the sendemail.php page?

francois

01.28.2010

<code></code>
sorry this seemed to fall of the last time.

francois

01.28.2010
define('EMAIL','me@domain.com');
define('SUBJECT','contact');
define('MAILFROM','info@domain.com');
$surname $_POST['surname'];
$message $_POST['message'];
$name $_POST['name'];
$street $_POST['street'];
$zip $_POST['zip'];
$city $_POST['city'];
$tel $_POST['tel'];
$email $_POST['email'];


foreach(
$_POST['check'as $value{
$check_msg 
.= "Checked: $valuen";
}


$body 
'naam:' $name "n" 'achternaam:' $surname "n" 'street: ' $street "n"'zip: ' $zip "n" 'city: ' $city "n"'tel: ' $tel "n"'email: ' $email "n" .
 
'message: ' $message "n"  .  $check_msg;

mail(EMAILSUBJECT$body"From: ".MAILFROM); 

and again ;-)

Trevor

01.28.2010

@francois-
Do you have a link to the form?

Trevor

01.28.2010

@francois-
Looks like you have an error in your JavaScript. Also, when you submit the form without putting in anything, you get a PHP error.

Joel

02.04.2010

Hey-thanks for this!  It works great for my needs!
Joel

Nocleg

02.04.2010

It works great for my needs! thanks.

Karl

02.04.2010

would you know how i could get a pop-up window saying “your email has been sent” instead of having a new page? Thanks for your help!

Trevor

02.05.2010

@Karl-
Do you mean an alert?

Colin

02.05.2010

@Matt.

I’ve been testing out variations of your code and noticed that if you have slow net, like if you are running utorrent and your connection is maxed, the timings get all screwed up.

Is this because of setTimeout? Is there a better way to fade out and remove the success message then reload the original form with fadeTo?

I’m running mine with fadeTo instead of fadeOut and if I set the timeouts longer it works fine on slow net but if it’s slower then the times overlap and when pulling in my form again it removes the P thus removing my original P on form.

Page w/ form: http://fiftyonestudios.com/projects/web/submitform/contact/

Here’s what my code looks like at the moment:

$(document).ready(function(){
 
$("#submit").click(function(){
  
$(".error").hide();
  
  var 
hasError false;
  var 
emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

  var 
nameVal = $("#name").val();
  if(
nameVal == ''{
   
$("#name").after('You forgot to enter your name.');
   
hasError true;
  
}
  
  
var emailFromVal = $("#emailFrom").val();
  if(
emailFromVal == ''{
   
$("#emailFrom").after('You forgot to enter your email address.');
   
hasError true;
  
else if(!emailReg.test(emailFromVal)) 
   
$("#emailFrom").after('Please enter a valid email address.');
   
hasError true;
  
}
  
  
var subjectVal = $("#subject").val();
  if(
subjectVal == ''{
   
$("#subject").after('You forgot to enter the subject.');
   
hasError true;
  
}
  
  
var messageVal = $("#message").val();
  if(
messageVal == ''{
   
$("#message").after('You forgot to enter the message.');
   
hasError true;
  
}


  
if(hasError == false{
   
$(this).hide();
   $(
"#sendEmail li.buttons").append('');
   
   $.
post("sendemail.php",
       
{ namenameValemailFromemailFromValsubjectsubjectValmessagemessageVal },
        function(
data){
      
$("#sendEmail").fadeOut(400, function() {       
       
$("img#loading").remove();
       $(
"#sendEmail").before('Success!Message sent. Thank you and have a great day!');
       
setTimeout(function() {
        
$("#contact_form p").fadeOut(400);
       
}2500);
      
});
        
}
    
);
    
setTimeout(function() {
     
$("#sendEmail").fadeIn(600);
     $(
"form p").show();
     $(
"#submit").show();
    
}5000);
    
  
}
  
return false;
 
});
}); 

Colin

02.05.2010

alright i must be doing something wrong but anyway… a better way to implement what I have above @ the link is very welcomed. It seems to run smooth and have no issues on a one tabbed browser but like I said above the timings get jacked up if your netspeed is low.

Colin

02.05.2010

@Trevor-

Thanks for cleaning up my posts!

Also, I was curious if there was a way to clear all the form fields on the fadeIn back to the default. In Firefox 3.5 all the information you just submitted seems to stay in the fields, but is that just a Firefox thing?

Trevor

02.05.2010

@Colin-
Sure, you can do that. Check out the jQuery API to see everything that you can do.

Colin

02.05.2010

@Trevor-

this seems to work…

$('#sendEmail')[0].reset(); 

Karl

02.06.2010

Hi Trevor, I found the solution to my previous post. I have another request though. I don’t speak english very well so I hope you’ll understand me.

I would like the visitor of my page to indicate three different names into three different boxes. How can I do to get the content of the three boxes into the message of my email? Would this complicate the script too much?

Trevor

02.06.2010

@Karl-
You should just add new fields to the form and process them with the JavaScript and PHP.

Karl

02.06.2010

Yeah but i am a little bit lost. I am very new to this. I tried to do what you say and the email couldn’t be sent. Is it what you would do for the JS?

var secondboxVal = $("#secondbox").val();
if(
messageVal == ''{
 
$("#secondbox").after('Veuillez renseigner le prenom et nom de la premiere personne.');
 
hasError true;

Trevor

02.06.2010

@Karl-
No, you just assigned the value to secondboxVal, so that is what you want to use in your conditional statement.

Karl

02.06.2010

Let me be more clear:

Index file
Second box name

Verify file

if($_POST['secondbox'== ''{
 $messageError 
'     bla bla bla.';

Submitform.js file

var secondboxVal = $("#secondbox").val();
if(
messageVal == ''{
 
$("#secondbox").after('Veuillez renseigner le prenom et nom de la premiere personne.');
 
hasError true;

Sendemail.php file

$message $_POST['message']

Trevor

02.06.2010

@Karl-
I can’t look at those bits and say that is all correct, but those are all areas you will need to modify.

Karl

02.06.2010

I understand. Let me just ask you a last question.

Would the sendemail file look like that? I have added two times “messagesecond” below but I am really not sure.

$mailFrom $_POST['emailFrom'];
$subject $_POST['subject'];
$message $_POST['message'];
$messagesecond $_POST['messagesecond'];

   
mail('xxxxx@gmail.com'$subject$message$messagesecond"From: ".$mailFrom);
?> 

Trevor

02.06.2010

@Karl-
You need to adjust your parameters for the mail function. You can’t pass in $message and $messagesecond; you should concatenate the strings.

Karl

02.06.2010

Thank you for your time, Trevor. I don’t know how to concatenate both of them but i will try to find on google. Thanks again!

Mark

02.08.2010

Very helpful.  I modified your code to make an “add comment” pop-up on one of my sites.  To see it in action, go to this link and click “Add Your Comments…” link.  Thanks!

http://www.everygoodbook.com/detail/296

Sam

02.09.2010

I had a look at a BUNCH of other options, but yours won out based on ease of use, lightness of the code and accessibility. Thanks for posting it!!

My version is in coldfusion, and equally accessible as the one you’ve made. If anyone ever needs the cfm code, let me know, I’m happy to share.

Jason

02.11.2010

How would you change the background color of the input field when there is an error (instead of having the error message appear as text)?

Thanks.

Trevor

02.11.2010

@Jason-
Instead of inserting the spans, just add a class to the form field.

Kreshnik

02.14.2010

hi i am new to coding and i was just wondering why in my contact form it is showing me the PHP code at the “” box.  this is my contact.html code:

Kontaktoni Klaudia Construction 

<!-- Form validation  starts here-->

<!-- 
Form validation ends here-->


    $(
document).ready(function(){
        
$(document).pngFix();
    
});


<!--
[if lt IE 8.]>-->

 <!--
[if lt IE 7.]>-->

<!-- 
Content Slider -->
  var 
flashvars {};
  
flashvars.xml "config.xml";
  
flashvars.font "font.swf";
  var 
attributes {};
  
attributes.wmode "transparent";
  
attributes.id "slider";
  
swfobject.embedSWF("design3edge.swf""content_slider""575""265""9""expressInstall.swf"flashvarsattributes);


<!-- 
Content Slider -->

<!-- 
Main Body Starts Here -->

<!-- 
Header Starts Here -->

<!-- 
Header Top -->

<!-- 
Header Top -->

<!-- 
Header Body Starts Here -->

<!-- 
Header Left Part Starts Here -->

<!-- 
Logo Starts Here-->

<
a href="index.html" rel="nofollow"></a>

<!-- 
Logo Ends Here -->

<!-- 
Divider Starts Here -->

<!-- 
Divider Ends Here -->

<!-- 
Menu Links Starts Here -->
<
a href="index.html" rel="nofollow">Hyrje</a>
<
a href="about.html" rel="nofollow">Rreth Nesh</a>
<
a href="#" rel="nofollow">Sherbime</a>
<
a href="clients.html" rel="nofollow">Kliente</a>
<
a href="contact.html" rel="nofollow">Kontaktoni</a>
<!-- 
Menu Links Ends Here -->

<!-- 
Header Left Part Ends Here -->

<!-- 
Header Right Part Starts Here-->

<!-- 
Content Slider Starts Here -->
<
a href="http://www.adobe.com/go/getflashplayer" rel="nofollow">        
    </
a>
<!-- 
Content Slider Ends Here -->

<!-- 
Header Right Part Ends Here -->

<!-- 
Header Body Ends Here -->

<!-- 
Header Bottom-->

<!-- 
Header Bottom -->

<!-- 
Header Ends here -->

<!-- 
Content Body Starts here -->

<!-- 
Left Content Starts Here -->

<!-- 
Heading -->

CONTACT US

<!-- Heading -->

"Vivamus sit amet odio pellentesque odio faucibus tristique. Morbi facilisis, 
ligula a faucibus pellentesque, orci justo consequat massa, sit amet dapibus
dolor diam viverra mi"

Vivamus sit amet odio pellentesque odio faucibus tristiqueMorbi facilisis,
ligula a faucibus pellentesqueorci justo consequat massasit amet dapibus 
dolor diam viverra mi
.
Lorem ipsum dolor sit ametconsectetur adipiscing elitNam pulvinar nisi eu enim facilisis dapibus.
Duis viverra turpis vitae dui tincidunt eleifendEtiam sodalesneque in dignissim dictumdui libero
dictum orci
vel cursus felis velit vitae dui

Vivamus sit amet odio pellentesque odio faucibus tristiqueMorbi facilisis
ligula a faucibus pellentesqueorci justo consequat massasit amet dapibus
dolor diam viverra mi
Aenean porttitorlectus at dapibus egestastellus ipsum
rhoncus orci
.

<!-- 
Form Starts Here -->
  
Send An Email
  
All fields are required
  
      From
<input type=&quot;text&quotname=&quot;emailFrom&quotid=&quot;emailFrom&quotvalue=&quot;<?php if(isset($emailFromError)) echo &#039;'.$emailFromError.''; ?>
   
Subject<input type=&quot;text&quotname=&quot;subject&quotid=&quot;subject&quotvalue=&quot;<?php if(isset($subjectError)) echo &#039;'.$subjectError.''; ?>
   
Message<?php if(isset($messageError)) echo &#039;'.$messageError.''; ?>
   
Send Email &raquo;
<!-- 
Form Ends Here -->

<!-- 
Left Content Ends Here -->

<!-- 
Right Content Starts Here -->

<!-- 
Contacts Starts Here -->
<!-- 
Heading -->
Kontaktoni:
<!-- 
Heading -->

Klaudia Shpk
Rr
Muhamet Gjollesha 
P.56 Sh.1 Ap.8
Tirana
-Shqiperi
Telefon
: <b>+355 682066757</b>
Telefon: <b>+355 682055758</b>
Email: <b>klaudia.shpk@yahoo.com</b>
Email: <b>mrdajti@yahoo.it</b>
<!-- 
Contacts Ends Here -->

<!-- 
Testimonial Starts Here -->
<
a href="http://maps.google.com/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Tirane&amp;sll=51.520755,-0.158628&amp;sspn=0.005795,0.013797&amp;ie=UTF8&amp;hq=&amp;hnear=Tirana,+Albania&amp;ll=41.329518,19.806247&amp;spn=0.009668,0.012875&amp;z=15&amp;iwloc=A" rel="nofollow">View Larger Map</a>
<!-- 
Testimonial Ends Here -->

<!-- 
Follow Us Starts Here -->

<!-- 
Heading -->
FOLLOW US ON
<!-- Heading -->

<
a href="#" rel="nofollow"></a> <a href="#" rel="nofollow"></a>
 <
a href="#" rel="nofollow"></a>

<!-- 
Follow Us Ends Here -->

<!-- 
Right Content Ends Here -->

<!-- 
Clear -->

<!-- 
Clear -->

<!-- 
Content Body Ends Here -->

<!-- 
Footer Starts Here -->

<!-- 
Top -->

<!-- 
Content -->
<
a href="index.html" rel="nofollow">Hyrje</a> | <a href="about.html" rel="nofollow">Rreth Nesh</a> | <a href="#" rel="nofollow">Sherbime</a> |
<
a href="clients.html" rel="nofollow">Kliente</a> | <a href="contact.html" rel="nofollow">Kontaktoni</a>

&
copyCopyright 2010. Klaudiaconstruction-alAll Rights Reserved

<!-- Clear -->

<!-- 
Clear -->

<!-- 
Content -->

<!-- 
Bottom -->

<!-- 
Footer Ends Here -->

<!-- 
Main Body Ends Here --> 

please help me how to fix it…
regards
Nik

Trevor

02.14.2010

@Kreshnik-
You already emailed me and did not give any details about what is not working. It’s challenging for anyone to help if you don’t provide any information about what isn’t working.

Kreshnik Pacara

02.14.2010

@Trevor-
SIR i told you it is showing me the PHP code at the input box i swear i am getting mad cuz i really like you from the way how it flip up on submit. if you can check would be great Trevor, please have a look at klaudiaconstruction-al.com/contact.html
from which address are supposed to come those comments at my website contact form??

Trevor

02.14.2010

@Kreshnik Pacara-
You can’t have PHP code on an HTML page.

Kreshnik Pacara

02.16.2010

@Trevor-
thanks Sir. i fixed the problem but another problem came :(  sorry for disturbing you so much but i really love your contact form ...!
At the sendEmail.php i added my e-mail address and when i test my contact form all e-mails comes to Junk Folder and the message look like this:

http://img237.imageshack.us/img237/295/emailfrom.jpg

at the host provider is a solution about host admin e-mail:

http://helpdesk.fastdomain.com/index.php/kb/article/206

and i did the solution 2 but the solution 1 i really don’t know how to do…?! :(

At the sendEmail.php this is what is written:


Wish you best regards…
God bless you

Kreshnik Pacara

02.16.2010

@Trevor-
placement of the message and subject resolved but the only one thing is comes to JUNK FOLDER.
thank you so much

Trevor

02.16.2010

@Kreshnik Pacara-
You should talk to your host about that.

Kreshnik Pacara

02.16.2010

hello, could anyone tell me which are the steps if i would like to add another box called “Name” at this contact form:

http://klaudiaconstruction-al.com/contact.php
thanks
nik

Trevor

02.16.2010

@Kreshnik Pacara-
You just need to duplicate what was done for another field. If you read through the comments, you will probably find more help too.

Bob S.

02.21.2010

Hi Trevor,

Question - your form works properly on my server with javascript enables in my browser. However, if I disable javascript, the form stops working, ie no validation, no success message and no email on the recipient end.

I’ve noticed that the form action of your Ajaxed demo points to the non-Ajax version of the form. My question is whether I will need to run two copies of the form - one ajax, one non-ajax - in order to accommodate my non-javascript users, or is the Ajax version form supposed to degrade?

Thanks.

Trevor

02.21.2010

@Bob S.-
In this example, you have to duplicate the validation, just like I did. But the actual sending of the email is using the same code.

Bob S

02.21.2010

Hey Trevor,

The thing that’s throwing me is that in your non-ajax demo, the form action just refers back to itself.

http://trevordavis.net/play/jqueryAjaxForm/

There’s no apparent link to either a form processor or validation script/verify.php in your non-ajax example, bringing me to the questions:

1 - where/how is the form procesing being done?

2 - where/how is form validation being carried out?

There’s obviously something very basic I’m missing here….

Thanks,
-Bob S

Trevor

02.21.2010

@Bob S-
Did you download the files at the end of the post? That should answer all of your questions.

Bob S

02.21.2010

You know, the light bulb started to go on shortly after my last post to you….I did start out with those files, and won’t go into the series of absolutely boneheaded mistakes that lead me here for help this afternoon, but suffice it to say it all started with forgetting to turn off “display_errors” in my php.ini this morning after troubleshooting another script. My money says that you can probably piece it together from there…

Anyway, all sorted out now. Your form works great, and your help has been greatly appreciated.

Thanks,
-B

Meble

02.25.2010

Very nice tutorial :)

soumya

02.26.2010

how to get the anser immediately while typing the question itself but without pressing the submit button or enter button,using javascript?

Php Catalog

03.03.2010

Awesome..it helped me alot..

ricky

03.08.2010

Jquery Form Applications; A great compilation…
http://www.ueuh.com/internet/jquery-form-applications/

Mark Kumar

03.11.2010

Thank you soo much for sharing this. I’m new to jQuery and Ajax. So, I have been looking to something like this tutorial and your is very informative and to the point. Thanks for sharing. I will definitely use this on my site.

Mark Kumar

Sara Bruce

03.21.2010

Hello,
Excellent to be here.Fine effort buddy.

builder

03.25.2010

Very good tutorial. This is what I sought. Everything clearly explained. Great thanks!

Sean

03.28.2010

Hey mate.
Just wanted to say thank you for posting this, whilst the inital post was many years old as I got further down the comments I realised how much more recent it is and the updates / issues resolves within the comments so it’s great to see that it’s still up and running.

I’ve not attempted an implementation with it yet, how ever I will be doing so shortly. Hopefully all goes well and I can draw on any problems from the comments before contacting you. So it should be fine.

Thanks again for a concisive approach to such a topic.

Sean.

Sean

03.29.2010

Ok it seems I am in need of help. You’re obviously quite busy so I’ve zipped the files relative to my problem for your convenience as I require a push in the right direction as quickly as possible.

Download it here: [ link ]

In the zip you’ll find:
- footer.php
- sendemail.php
- submitform.js
- thanks.php
- verify.php

The file “footer.php” is where I’ve put the contact form for my website. It’s a modified version of the “index.php” file you provided to only contain what I need.

It may be worthy of note (if not obvious from reading the code already) That I’ve modded the form to contain a Name, Email, Subject and Message.

One other thing to note is that in my header file (not provided/needed) I’m calling the scripts:


Basically to help you along here, I’ve noticed that the contact form doesn’t actually show.

Once I remove the line in “footer.php” that includes the file “verify.php” from where it is located - The contact form then shows. So there must be some conflict here yet your example has the include of the same file in the same position?

The other thing was is my form action set up correctly?

I have placed thanks.php, verify.php and sendemail.php at the location of the folder “contactform” that you will see in the code. Am I correct in assuming those files are what is needed in there and then just to reference to that directory in my form action and if so then what is your oppinion on what has happened?

Thanks in advance.

Sean

03.29.2010

The code snippet I attempted didn’t seem to publish. Where I said “I’m calling the scripts:”

It was just code showing me calling the submitform.js and jquery.

Cheers.

Nauman Akhtar

04.02.2010

Do you have a Demonstration link I can look at?

Trevor

04.02.2010

Doctor Fox

04.03.2010

Great tutorial, would also be great if you mentioned that your jquery functions were in a separate file, and added the link to that file also, just like you did for the other files above .

Trevor

04.03.2010

@Doctor Fox-
The link to the full script is in the post.

Mark

04.04.2010

Love it.

Took some time to get working, but nevertheless is was worth the hassle!

Tried to modify some more which worked to some extent.. slowly I’m getting the hang of this.

This tutorial is not only awesome for making the ajax forms.. but in general I like the way it introduces ajax too!

I’ve bookmarked this page and will definitely look again when I need it ! :)

Chris

04.06.2010

Hey Trevor,

I’ve been attempting to get this form implemented and working in a section of my site; however, I am having some issues.

It seems that everything goes as planned, the form shows up, and once filled out/submitted, the thank you message displays, though it appears that the email never actually gets sent.

I’m new to PHP, but after looking at these files for as long as I have, the logic behind everything makes enough sense for me to understand what does what.

I have a test page up that I’ve been using while trying to get this running (please excuse the lack of images/styling)

http://205.186.140.46/products/product.php

All of the JS and PHP files are living in the /products/ directory

I have the form action pointing to the page itself - product.php

I edited the PHP files as I didn’t need any of the “Email To” functionality - all emails will be going to one specific inbox.  For testing purposes, i have been using my personal email.

I also edited the code in sendemail.php to reflect that change:

<code></code>

If there is any reason you can think of that might explain why the emails aren’t getting pushed, or just any tips/things to consider for that matter, i would greatly appreciate it.

Thanks in advance.

Chris

04.06.2010

After looking over the code time and time again, I just rewrote everything from scratch, and now it works.  I’m still not quite sure what I wasn’t seeing the first time(s) around, but it’s working - can’t complain too much.

Thanks for the tutorial!

Stacey

04.10.2010

Hi Trevor,
I am a new graduate from graphic/web design, and they never taught us anything about PHP.
I am attempting to better myself and learn more on my own time.
I want to use this contact box on my website, and, as you can see, it goes on fine, but doesn’t work.
I have no idea what to do with the PHP, and where to put the PHP.
Any advice?

Trevor

04.10.2010

@Stacey-
They have lots of tutorials online. Honestly though, if you have never heard of PHP, this is probably not the contact form you will want to use.

Stacey

04.10.2010

Well, Trevor.
I want to teach myself things, because my school didn’t.
Thanks, though, for the link.

jaming

04.22.2010

I Trevor

I suppose that the analytics.php file included in the thanks.php one could just contain a script like the analytics code, just plain simple, no (php) echoing envolved.

I’m prety sure I’m right, but just wanted to know your opinion.


Cheers and thanks by the way ;)

Trevor

04.23.2010

@jaming-
Yes, I should have removed it from the file; it was just used for including my Google Analytics code.

puck

05.04.2010

Just wanted drop a quick line that this helped me out nicely today and is just a nice little piece of easily digested knowledge. In addition, it was really easy to break apart and throw right in the mix with a bunch of other stuff.
Thanks!

Michael

05.10.2010

Great script!

I have 2 quick questions.

1) How do I get my form to disappear when the form has been submitted and processed successfully?

2) Can I still do PHP processing in case they have Javascript disabled? Is that what the verify.php file is for?


Thanks for your time in reading this comment.

Matt G.

06.01.2010

This is all fine and dandy and gives the user a more pleasant experience, but remember that all data should be validated on the server side also.  Its way to easy to bypass the form entirely.  NEVER TRUST USER DATA ON THE SERVER SIDE!  And as a side note.  You’re going to want to use captcha or else you’re going to be bombarded with viagra ads once the bots find your form(s).

Matt G.

06.01.2010

@Michael-

Michael,

As a rule of thumb you should always do php (or other server language) validation.  Forms are easily bypassed therefore all of the JavaScript validation is easily bypassed.

Michael

06.02.2010

@Matt G.-

Thanks, Matt.

I will play about with the verify.php script and get my server side validation up to speed. Will let you know how it goes :)

Mike

06.13.2010

@seb-
Neat

Ash

06.18.2010

Hi, i’m using this code and everything’s working fine except the sendEmail.php is opening a blank page and i have no idea why.  Any idea where i went wrong?

waldemar

06.18.2010

Great explanation, would also be good as Noah is YOUR jquery functions available in a separate file, and added Turn This word also learn to die, net, as is done for the other Displayed above.

wpdeveloper

06.21.2010

very nice tutorial. I have learned a lot. Big thanks to Trevor :)

wpdeveloper

06.21.2010

I have learned lot from this tutorial. Thanks buddy :)

Once again big thanks to Trevor :)

Sub

06.27.2010

Hi!
Do you plan to implement some captcha code into the form processing routine? Or did it somebody already?
Thanks

Trevor

06.27.2010

@Sub-
I don’t have any plans to, but you could easily add CAPTCHA yourself.

Justin

06.27.2010

This is a great tutorial! Fast and easy to configure/edit.
Bookmarked for future reference.

Thanks Trevor.
——-

Andrew

07.15.2010

Hi guys,

I’m trying to find a form that will allow my customers to upload artwork via our website and us to receive it via email.

Any ideas please. It would need to fit nicely into a product page.

Cheers
Andrew

test

07.25.2010

test

Glennyboy

07.25.2010

Hi

Figured out mush of your script and it works well!

My question is can your validation be replaced by the jquery validation plugin as found here:-

http://docs.jquery.com/Plugins/Validation

This would make validation a lot easier, but the form seems to be skipping and going straight to submit of form.

Thanks

Glennyboy

Trevor

07.25.2010

@Glennyboy-
Sure, you could adjust the code to use that validation plugin.

Glennyboy

07.26.2010

Hi Trevor

That’s great. Are you able to give some pointers?

Cheers
Glennyboy

Glennyboy

07.26.2010

Not to worry Trevor I simply uncommented your own validation and added in the JQuery validation to the page. Works well.

Dude, amazing tutorial

What do you have to say?