Ajax Forms with jQuery
Posted on September 8, 2007 in Tutorial | 111 Comments »
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:
- User fills out the form.
- User submits the form to the server.
- Server side script makes sure that there are no blank fields and that the email addresses are valid.
- If there are errors, show the form again with the error messages.
- 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",
{ emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },
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:

























Ronald AllanSeptember 8, 2007 at 1:49 pm
ei thanks! i will try this code.. actually i need this kind of code for my new project.
thanks again!
DeanSeptember 9, 2007 at 1:05 pm
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?
TrevorSeptember 9, 2007 at 2:24 pm
@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 HemphillSeptember 17, 2007 at 2:51 am
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.
TrevorSeptember 17, 2007 at 9:21 am
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”.
huljoSeptember 19, 2007 at 2:23 am
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?
TrevorSeptember 19, 2007 at 9:15 am
@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.
jackDecember 20, 2007 at 12:04 pm
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?
TrevorDecember 21, 2007 at 12:18 am
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 BaileyJanuary 21, 2008 at 3:00 pm
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!
TrevorJanuary 24, 2008 at 2:29 pm
@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 MallowFebruary 16, 2008 at 7:11 am
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
TrevorFebruary 16, 2008 at 8:05 pm
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.
PaoloFebruary 24, 2008 at 4:38 pm
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 …
TrevorFebruary 24, 2008 at 9:08 pm
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.
PaoloFebruary 25, 2008 at 4:10 am
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.
PaoloFebruary 25, 2008 at 5:44 am
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.
TrevorFebruary 25, 2008 at 10:08 am
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?
PaoloFebruary 25, 2008 at 11:21 am
“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”,
{ Language: LangVal, Email: EmailVal, subscribe: SubVal },
function(data){
if(data){
$(“#message”).text(‘Your request was sent.’);
} else {
$(“#message”).text(‘An error occurred. Your request could not be sent.’);
} …
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!
TrevorFebruary 26, 2008 at 11:37 pm
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 HaiderMarch 10, 2008 at 1:27 pm
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!
FiqhiMarch 16, 2008 at 9:54 pm
This is what I’m looking for! thanks trevor :)
JohanMarch 18, 2008 at 2:16 pm
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. ;)
TrevorMarch 18, 2008 at 6:21 pm
Johan-
I actually did upload the final PHP code. If you look at the end of the post, you can download them there.
FabiánMarch 21, 2008 at 11:11 pm
It seems that the validation can only be done client-side, am I right?
TrevorMarch 22, 2008 at 12:28 am
@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.
johnApril 8, 2008 at 4:21 pm
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?
TrevorApril 8, 2008 at 8:59 pm
@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.
MartinMay 21, 2008 at 4:26 pm
Very good and useful , but it doesn’t work with Prototype JavaScript (http://www.prototypejs.org) at once used in Lightbox(http://www.huddletogether.com/projects/lightbox2/).
Do you have an idea why? Thanks for answer, regards.
TrevorMay 21, 2008 at 8:51 pm
@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!
AlexJune 10, 2008 at 5:53 am
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.
ggJune 11, 2008 at 3:41 am
I could not find “jqueryAjaxForm”
ggJune 11, 2008 at 3:44 am
And I could not find success message as I submitted the comment.
KeenahnJune 26, 2008 at 12:50 pm
This is an excellent intro to jQuery. Kudos!
-K
DarriousJune 29, 2008 at 11:44 pm
I was wondering if anyone knew how to get radio buttons working? I’m having a tough trouble with getting them to work.
TrevorJune 30, 2008 at 8:40 am
@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?
DarriousJune 30, 2008 at 3:55 pm
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.
TrevorJune 30, 2008 at 10:36 pm
@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.
Again, there are a bunch of different ways to achieve this.
sebJuly 6, 2008 at 6:50 pm
cool
jamesJuly 19, 2008 at 6:52 pm
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.
TrevorJuly 19, 2008 at 8:42 pm
@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.
Devich » Blog Archive » Radio button controlJuly 24, 2008 at 10:53 pm
[…] Ajax Forms with jQuery […]
joshAugust 3, 2008 at 2:42 am
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:)
25 Awesome tutorials for web designers « Narendra DhamiAugust 11, 2008 at 9:01 pm
[…] 11. Ajax Forms with jQueryTravor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
25 Awesome tutorials for web designers « Guiwells’s BlogAugust 12, 2008 at 1:31 am
[…] 11. Ajax Forms with jQueryTravor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
From free for free » Blog Archive » 25 Awesome tutorials for web designersAugust 12, 2008 at 5:25 am
[…] 11. Ajax Forms with jQueryTravor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
25 Awesome tutorials for web designers | Boxed CSSAugust 16, 2008 at 10:54 am
[…] 11. Ajax Forms with jQueryTravor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
25 Awesome tutorials for web designers | Boxed CSSAugust 16, 2008 at 10:54 am
[…] 11. Ajax Forms with jQueryTravor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
benjaminAugust 25, 2008 at 5:23 am
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
TrevorAugust 25, 2008 at 8:50 am
@Benjamin-
You would do it the same way you would any other input field.
Christoph G.September 2, 2008 at 8:38 am
Thanks a lot for sharing so good inputs!
ChrisSeptember 2, 2008 at 7:48 pm
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 info@creativehinge.com
Thanks for any help you can provide.
TrevorSeptember 2, 2008 at 8:22 pm
@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:
Hope that helps.
ChrisSeptember 2, 2008 at 8:59 pm
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…
TrevorSeptember 2, 2008 at 10:01 pm
@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.
ChrisSeptember 2, 2008 at 11:17 pm
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
TrevorSeptember 2, 2008 at 11:40 pm
@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.
ChrisSeptember 2, 2008 at 11:43 pm
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
ChrisSeptember 2, 2008 at 11:44 pm
here’s all my verify code:
ChrisSeptember 2, 2008 at 11:47 pm
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
TrevorSeptember 2, 2008 at 11:50 pm
@Chris-
Yes, just remove all of this from verify.php:
Then, change line 22 of verify.php to be:
That should do it.
ChrisSeptember 2, 2008 at 11:50 pm
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) && !isset($emailFromError) && !isset($subjectError) && !isset($messageError)) {
include(‘form/sendEmail.php’);
include(‘form/thanks.php’);
}
}
ChrisSeptember 3, 2008 at 12:04 am
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?
TrevorSeptember 3, 2008 at 12:08 am
Chris-
Yep, that should still work. I would remove this line since you removed the emailTo field:
ChrisSeptember 3, 2008 at 12:14 am
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?
TrevorSeptember 3, 2008 at 12:25 am
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?
ChrisSeptember 3, 2008 at 12:39 am
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!
25 Awesome tutorials for web designers | 打篮球的手September 8, 2008 at 6:26 am
[…] 11. Ajax Forms with jQuery Travor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
RSSA聚合 » 25 Awesome tutorials for web designersSeptember 9, 2008 at 5:44 am
[…] 11. Ajax Forms with jQuery Travor Davis illustrates how easy it is to turn a regular form into a AJAX form. […]
2008 September 11 - Links for today « My (almost) Daily LinksSeptember 11, 2008 at 1:01 am
[…] jQuery with Dynamic Data Customizing the Delete Confirmation Dialog Trevor Davis gives us a take on AJAX Forms with jQuery James Padolsy brings us his 10 useful jQuery plugins Dossy Shiobara brings us Client-side query […]
Kerwin GrootSeptember 11, 2008 at 6:15 am
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: http://www.kerwin-groot.nl/upload/contactForm.zip
Rafa GarciaSeptember 12, 2008 at 7:08 am
Simple as good things are.
Dave BrookesSeptember 25, 2008 at 5:29 pm
@ 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
FedericoSeptember 27, 2008 at 4:54 am
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
TrevorSeptember 27, 2008 at 10:00 pm
@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?
FedericoSeptember 28, 2008 at 3:16 am
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!
TrevorSeptember 29, 2008 at 3:56 pm
@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:
Jake RutterSeptember 30, 2008 at 4:32 pm
Great Tutorial! Thanks!
JoeOctober 6, 2008 at 2:20 am
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)
TrevorOctober 6, 2008 at 9:13 am
@Joe-
You will need to modify the sendEmail.php file and add in your new fields to the email.
links for 2008-10-08 | 甘先生blogOctober 8, 2008 at 4:05 am
[…] Ajax Forms with jQuery | Trevor Davis (tags: ajax:form) […]
Clemente GOctober 9, 2008 at 12:04 am
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??
TrevorOctober 9, 2008 at 12:10 am
@Clemente G-
Do you have a link I can take a look at?
JoeOctober 13, 2008 at 10:03 am
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 ?
TrevorOctober 13, 2008 at 11:51 am
@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.
JoeOctober 13, 2008 at 12:03 pm
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 ! ;-)
EduardoOctober 13, 2008 at 11:02 pm
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?
EduardoOctober 13, 2008 at 11:15 pm
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?
TrevorOctober 14, 2008 at 9:23 am
@Eduardo-
No, it does submit the form via an AJAX request.
EduardoOctober 15, 2008 at 3:06 am
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?
TrevorOctober 15, 2008 at 10:22 am
@Eduardo-
Are you sure you have the POST request submitting to the correct URL? So you said it works without JavaScript?
EduardoOctober 15, 2008 at 1:04 pm
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.
EduardoOctober 15, 2008 at 7:09 pm
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!
TrevorOctober 15, 2008 at 7:29 pm
@Eduardo-
Nice, I was going to suggest something was up with the config. Glad you got it working.
50 Excellent AJAX Tutorials | Tutorials | Smashing MagazineOctober 16, 2008 at 5:46 pm
[…] AJAX Forms with jQuery Trevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
Useful AJAX Tutorials | Neurosoftware web devOctober 17, 2008 at 2:58 am
[…] AJAX Forms with jQuery Trevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
amirOctober 17, 2008 at 4:12 pm
thanks
50 Excellent AJAX Tutorials | POLPDESIGNOctober 18, 2008 at 3:13 am
[…] AJAX Forms with jQuery Trevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
50 Excellent AJAX Tutorials | Web Burning BlogOctober 18, 2008 at 4:05 am
[…] AJAX Forms with jQueryTrevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
hm2kOctober 20, 2008 at 9:47 pm
Beware of email injection with php’s mail() function, google it.
50+ Great Ajax Tutorial | Tech User, Blogger and Designers ReferencesOctober 21, 2008 at 7:34 am
[…] AJAX Forms with jQuery Trevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
EduardoOctober 21, 2008 at 4:03 pm
h2mk:
Good point, but wouldn’t the server side regEx validation for email address be enough to be safe?
Melhores tutoriais para desenvolvimento com AJAX - parte 1 | TuisterOctober 22, 2008 at 8:16 am
[…] Formulários AJAX com jQuery […]
Martin EdwardsOctober 23, 2008 at 6:50 am
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’);
}
}
Blog Me I’m famous » 16 exemples et sources de formulaires AjaxOctober 25, 2008 at 10:27 am
[…] jQuery Contact Form - Demo […]
16+ Ücretsiz Ajax İletişim Formu | Batuhan BulakOctober 26, 2008 at 11:03 am
[…] jQuery Contact Form | Demo […]
Подборка AJAX скриптов | Екатеринбургский ПЕШЕХОДOctober 28, 2008 at 7:16 am
[…] AJAX Forms with jQuery […]
50 Excellent AJAX Tutorials | Evolution : weblogOctober 31, 2008 at 12:24 am
[…] AJAX Forms with jQuery Trevor Davis shows how to create a form that will check an email address for validity, makes sure there are no blank fields and display an error if something isn’t right or complete. […]
EduardoNovember 18, 2008 at 5:30 pm
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?
TrevorNovember 18, 2008 at 9:19 pm
@Eduardo-
Actually, this is a similar problem that Darrious had.
Check out the sample page or see my response to Darrious.
EduardoNovember 18, 2008 at 9:41 pm
@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.