Ajax Forms with jQuery

Posted on September 8, 2007 in Tutorial | 28 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:

  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",
   { 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:

28 Responses

  1. 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!

  2. 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?

  3. 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?

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

  5. 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”.

  6. 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?

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

  8. 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?

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

  10. 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!

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

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

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

  14. 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 …

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

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

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

  18. 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?

  19. 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!

  20. 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!

  21. 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!

  22. FiqhiMarch 16, 2008 at 9:54 pm

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

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

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

  25. FabiánMarch 21, 2008 at 11:11 pm

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

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

  27. 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?

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

Speak Your Mind

* Denotes Required Field

  1. Sick of filling out this form? Register or Log in now.

Who Am I?

Trevor Davis I’m Trevor Davis, a 23 year old Front-End Developer. Basically, I make web sites.

By day, I work for Matrix Group International in Alexandria, VA, and by night, I freelance.

Feel free to get in touch with me about anything.

What Have I Done?

  • Direct Selling 411
  • Makeup Bizz
  • InstallNET
  • National Park Foundation
  • Worldwide Breast Cancer
  • Food Marketing Institute
  • MatrixMaxx
  • National Park Foundation Leadership Summit

View All My Work »

Bookmarks

View All My Bookmarks »