A quick and easy AJAX Contact Form Tutorial using PHP and jQuery. I decided to put this together as I’ve received comments from a number of people who like the AJAX contact form on my main site.
VIEW THE DEMO (note, in the demo, I have commented out the line which actually fires the email) | DOWNLOAD THE FILES
As a base line, we will take the standard PHP contact form example on W3schools. We’ll throw in some jQuery and CSS and modify it slightly to make it to work with AJAX. This is what we will start with:
<html> <body> <?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("[email protected]", $subject, $message, "From:" . $email); echo "Thank you for using our mail form"; } else //if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text'><br> Subject: <input name='subject' type='text'><br> Message:<br> <textarea name='message' rows='15' cols='40'> </textarea><br> <input type='submit'> </form>"; } ?> </body> </html> |
The first thing you will want to do is to separate the code which actually sends the email from the display of the form so you will have two files:
index.php
<html> <head> <title>AJAX Contact Form with PHP and jQuery</title> </head> <body> <form method='post' action='mailform.php'> Email: <input name='email' type='text'><br> Subject: <input name='subject' type='text'><br> Message:<br> <textarea name='message' rows='15' cols='40'></textarea><br> <input type='submit'> </form> </body> </html> |
mailform.php
<?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("[email protected]", $subject, $message, "From:" . $email); echo "Thank you for using our mail form"; } ?> |
We will be using jQuery.ajax() to post the form data through to the send script which requires no further modifications (you can also use jQuery.post() as a slightly simpler way of doing this but I always opt for ajax() as it offers a greater amount of control if needed). But first we need to add a loading indicator and a success message. Both of which will be initially hidden via the CSS. With jQuery, we will show and hide these at the appropriate stage of the process:
index.php
<html> <head> <title>AJAX Contact Form with PHP and jQuery</title> <style> #loading, #success{display: none} </style> </head> <body> <form method='post' action='mailform.php'> Email: <input name='email' type='text'><br> Subject: <input name='subject' type='text'><br> Message:<br> <textarea name='message' rows='15' cols='40'></textarea><br> <input type='submit'> </form> <div id="loading"> Sending your message.... </div> <div id="success"> </div> </body> </html> |
Now the jQuery. With the jQuery we will:
- Prevent the default form action
- Hide the form
- Display the “loading” message
- Post the form to the send script
- Wait for a successful response
- Hide the “loading” message
- Display the “success” message
$(function(){ $('form').submit(function(e){ var thisForm = $(this); //Prevent the default form action e.preventDefault(); //Hide the form $(this).fadeOut(function(){ //Display the "loading" message $("#loading").fadeIn(function(){ //Post the form to the send script $.ajax({ type: 'POST', url: thisForm.attr("action"), data: thisForm.serialize(), //Wait for a successful response success: function(data){ //Hide the "loading" message $("#loading").fadeOut(function(){ //Display the "success" message $("#success").text(data).fadeIn(); }); } }); }); }); }) }); |
Here is the complete code:
<html> <head> <title>AJAX Contact Form with PHP and jQuery</title> <style> #loading, #success{display: none} </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function(){ $('form').submit(function(e){ var thisForm = $(this); //Prevent the default form action e.preventDefault(); //Hide the form $(this).fadeOut(function(){ //Display the "loading" message $("#loading").fadeIn(function(){ //Post the form to the send script $.ajax({ type: 'POST', url: thisForm.attr("action"), data: thisForm.serialize(), //Wait for a successful response success: function(data){ //Hide the "loading" message $("#loading").fadeOut(function(){ //Display the "success" message $("#success").text(data).fadeIn(); }); } }); }); }); }) }); </script> </head> <body> <form method='post' action='mailform.php'> Email: <input name='email' type='text'><br> Subject: <input name='subject' type='text'><br> Message:<br> <textarea name='message' rows='15' cols='40'></textarea><br> <input type='submit'> </form> <div id="loading"> Sending your message.... </div> <div id="success"> </div> </body> </html> |
Obviously, there is no validation or styling on the form, it is simply a quick demo on how to make a working contact form using AJAX with PHP and jQuery. If you’d like me to expand on this and incorporate validation and some nice styling, let me know in the comments below and I will write another post to take this contact form a stage further.
Any questions? Feel free to ask.
Want to hear me talk? I co-host the web development podcast “Three Devs and a Maybe”. Check us out here
Hi
Hi
Great stuff. Worked like a charm. If you decide to put up the validation walk through let me know. Would love to put that in.
Thanks!
Glad it was of help
Will get to work on a new one with validation. Hopefully sometime over the coming weekend.
Great tutorial, thanks for that!
No probs! Glad it was of good use
$(“#success”).text(data).fadeIn(); will load “Thank you for using our mail form”, right?
The example works on localhost but i cant get to work when i implement it it just loads the sendmail script. Help!
Hi,
You should check your server’s php.ini to see if your mail function is set up correctly (if at all).
Cheers
Ty for quick reply I’l explain better. I run Xampp for Windows and i have 2 directories where 1st is mySite and 2nd is yourExample where i have files i downloaded above. yourExample works on localhost but when i try to implement the same code on mySite it just jumps to mailform.php when i submit.
I understand now. It sounds like there is a Javascript error as the e.preventDefault() function is not stopping the form from submitting in the standard way. Are you getting any error messages in your browser console. It could be possible that the external jQuery link is blocked from the 2nd environment?
Cheers
I believe that is the problem I’m using jQ div .load and lightbox I’l message you if i sort it out
Thank you Fraser! I was using the jQuery UI DatePicker plugin had been searching for quite some time to find a way to include AJAX form submission using jQuery. I had found a working script that used jQuery 1.3.2 but the version 1.9.1 needed for the DatePicker plugin created a conflict. Your script allowed me to run everything using 1.9.1 thus eliminating the jQuery conflict issue. I was then able to tweak it, save and link it as an external .js, and get everything working together. Thanks!
Glad it was of use, Drew! Always nice to hear positive feedback. Cheers!
It is very good but lacks VALIDATION… kindly add validation for the field which is the primary function now our days!
Hey there,
I’ve tried a lot of Form-Mailers now and I get stuck each time. Best result I got was Email but with dirty page-reload and without success-message. I now tried the version with php AND ajax and the result is: No Email, success-message = my whole index.html code ?? Any further information? (Oh yes, before I forget, why do you use REQUEST on form-fields?)
Can you post your code somewhere that I can take a look? Sounds like you may be getting a script error. In the returned data, are you getting any reference to any errors? Also, are you sure you’re running PHP in your dev environment? If not, then you will just be getting the text content of mailform.php returned rather than “Thank you for using our mail form”
Hey there, just look at flobuech.ch/
I took the return_msg out to not flood the page, but with right tools like forefox firebug or dev-tools you’ll be able to look at it, else just enter url of php on root…
Last but not least:
-everything is external, php and js. index is index.HTML.
-it worked before with overwritten version of php, but should do at this point too.
thx for having a look at it!
Hi again, not sure if my 3. comment has been submitted right, so:
First of all, I can’t see any script-errors, secondly there is no reference I can see. The returned output looks like the whole index.html like so:
bla
just like I coded it and not only the user-output of index.html.
Then, Yes PHP is running, but I’m only able to test online, maybe I should upload a test_data and do not just develop on my running page, but whatever…
Some part of it must work at least, cause the form is hiding before giving me a lot of nonsense-content.
I really hope you could help me!
Have some nice rowing 😉
Dude
Sorry for spaming but your form has sumbited my content wrong.
It means bla >’/’h’t’m’l’> and not just ‘bla’
EDIT 2: I hope you know what I mean cause it did again wrong. Just the whole input of the file just as i coded it with every tag from the hyper text markup language.
Hi there again,
(At first, please delete all pre-comments, looks pretty spamed)
I got it. Looked like it had problems with jquery.
Now it really sends the mail, but it calls the php like Srdjan told you.
I think it has something to do with the e.preventDefault() where you now should use – as I read (console + web) – e.isDefaultPrevented().
And at least the output is the same again when clicking back in browser. Whole hypertext…
Hey there,
another part “solved”, or however you’d call it. The point why I got my full markup back as output had to do with the “url: thisForm.attr(“action”)”. When I used “url: ‘mailformer.php'” instead it gave me back the right echo-message. Now it’s your turn to find out, specialist 😉
I literally tried like a dozen other contact forms this was the only one simple, customizable, and small enough to work for one of my clients. So thank you!
Thanks for the tutorial! It’s so simple and works so well… You mentioned possibly a future post expanding to incorporate validation and I for one would be very appreciative as I’ve had a lot of trouble with validation scripts and cross browser compatibility. Either way, thanks again! This has been so helpful..
Glad it helped
I’ll see if I can fit another tutorial in with validation.
Cheers!
Can you help me to create success or loading message on top of the form using your above code?
Can you post a link to a jsfiddle of your existing code, pls and I’ll see what I can do?
I would like to see error and success message on top of the form? (show 30 second only)
On double checking my tutorial, the loading message functionality is actually already in there, you will just need to style up #loading as you see fit.
Cheers
no, page complete loading instead of loading or refresh form DIV.
Hi,
Great Tutorial. It works like a charm.
Thank you!
Hi,
Great Tutorial. It works like a charm.
Thank you!
Great tutorial! I’d like to try this example within a WordPress theme. In WordPress all php scripts should be put in a separate file called functions.php. is it possible to make the form call a php function from this file without firing all other code inside?
Hi,
Could you please explain why did you use $_REQUEST instead of $_POST? Is it any reason for that?
Thanks,
Hi,
thank you for making this great ajax form tutorial. Everything is working for me, except that the form is submitting twice. How can I prevent this from happening?
AWESOME! THANK YOU!