Log In | Register | November 25, 2014

Share
 

jQuery Programming - September 7, 2010

Easy jQuery Ajax PHP Contact Form

In this tutorial, we are going to be creating a simple Ajax contact form which will allow us to post our form values to the processing file and return our results without any page refresh.

Before anything you should always start with your basic html. Set the page up the way you would like and then we will add the magic. In this case we will create a basic contact form with the following fields: name, email, and message.

<form action="process.php" method="post" id="contact_form">
<div>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="" tabindex="2" />
</div>
<div>
<label for="message">Message:</label>
<textarea cols="40" rows="8" name="message" id="message"></textarea>
</div>
<div id="loader">
<input type="submit" value="Submit" />
</div>
</form>

In the form above you will notice that we are setting the action to a process.php file. This file will create a basic PHP script that will process the post and send an email.

*Note: If you plan on using this mail script, please make sure you validate the fields to avoid any hacks.

The PHP file I created for process.php is as follows:

<?php
$toemail = 'test@youremail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(mail($toemail, 'Subject', $message, 'From: ' . $email)) {
echo 'Your email was sent successfully.';
} else {
echo 'There was a problem sending your email.';
}
?>

This file just creates basic variables to hold each of our posted values and then sends the email to the email assigned to the toemail variable. Simple enough.

Now it’s time for the magic. Lets add a bit of jQuery code to our index.php file and see what happens. First you need to remember to include the jQuery framework or none of this will work. I directly linked to the Google code bank for mine.

After linking the jQuery file, I set up the document ready function in the header. Within the document ready function I create a selector for the form that I want to apply this Ajax functionality to. In this case I gave my form the id of contact_form. So far your code should look like this:

<script type="text/javascript">
$(function(){
$('#contact_form').submit(function(e){
e.preventDefault();
});
});
</script>

Notice that I also passed though the e variable which I used to make sure the form would not be submitted to the next page using the .preventDefault() method.

Now that we have this part setup, it’s time to declare some variables. We need to get the URL we are posting to, and the data we are posting. In this tutorial I created 3 variables. 1 to hold the form, 1 for the URL, and 1 for the data.

var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();

Earlier when I created the form you will notice that one of the divs within the form that holds the submit button contains the id of loader. I’m going to add a line of jQuery to change out the html of that div with a loading gif. You will also notice that I used the JavaScript method serialize(). This method puts all of our posted values in a string for us to use.

$('#loader', form).html('<img src="loader.gif" /> Please Wait...');

*Note: This will just show a loading image with a note of Please Wait… while the form is submitted.

Now after that line, we want to create the Ajax functionality which will handle our post. The syntax is:

$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});

Using the $.ajax method, we are able to submit our data to the PHP script and return a result. We first start by defining the type as POST, since we will be making a Post to the document. For the URL parameter, we want to give it the variable we created post_url. This will let the Ajax function know that we want to post to that specific URL. The data parameter will store our posted values, so we want to give it our variable that we created of post_data. Lastly, the success parameter, which will take a function that, will return our result. Notice I am passing through the msg variable. This msg variable will store our result from the next page.

Within the success function you will also notice that I’m fading out the form and replacing its contents with the new msg returned from our post. (That is just for a nice visual effect.)

After that, you have completed the Ajax portion of the form. Save it and test it out. Your jQuery should look like the following:

<script type="text/javascript">
$(function(){
$('#contact_form').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
});
</script>

Attached are the files for you to download. Let me know if you have any issues.

Download PHP jQuery Ajax Contact Form

Post By: | FavoriteLoadingAdd to favorites

48 Comments

kyleinsea
Wednesday, September 8, 2010

Great Tutorial, simple and to the point. Thanks for the sample!

kyleinsea
Wednesday, September 22, 2010

This is a great form that works extremely well! My only problem is that I also need to add validation. In the past I’ve used Javascript, but it seems that my JQuery AJAX call is being executed before any of my other Javascript. What is the best way to handle this situation?

Frank Perez
Wednesday, September 22, 2010

I’ll post a part 2 to this tutorial soon, which will include validation. It’s actually very simple to add validation to a form.

Neil
Wednesday, December 1, 2010

Great tutorial, thanks.

On the process.php, I need to include the $name as part of the body of the email with the $message, do you know how I would combine those 2 fields?

Thanks

Frank Perez
Sunday, December 19, 2010

Hey Neil, you could simply concatenate them together.
$message = $name . “\n” . $_POST['message'];

uptraffic
Wednesday, February 16, 2011

Nice Tutorial, easy and to the exact point. Thanks for the post!but it seems that my JQuery AJAX call is being executed before any of my other Javascript. What is the best way to handle this situation?

buck Mont
Tuesday, February 22, 2011

Frank,

$message = $name . “\n” . $_POST['message'];
Gives me a bunch of errors. (unexpected T_VARIABLE)

I changed $message to $phone. Would like to include user $name, $email, and $phone within the body.

Frank Perez
Thursday, March 10, 2011

Would you be able to show me the rest of your script?

Anuj
Friday, April 22, 2011

Very well explained thanx dude!

Chris
Saturday, July 9, 2011

Thank you for this great script :-). I was wondering if you could help me with a bit of a modification? I’m trying to post the success message below the form instead of fading it out.

I know it is something to do with this portion of the script but i’m not sure what to replace it with?

success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();

Any help would be greatly appreciated.

Chris

zenith
Monday, October 17, 2011

i come across your blog during searching of jquery ajax form and found your post. It is very nice to suit with my web page.

Thanks for it.

commodity
Monday, October 17, 2011

one of the best solution to my problem. I am very thankful and appreciate your great work done.

soum
Tuesday, February 21, 2012

hi, i am trying to do the same thing as chris where i am trying to make the success message show under the form without fading out the form….dont see any comment on that…can anyone help me out with this? thanks in advance

sam
Sunday, March 11, 2012

nice tutorial..

Dan
Friday, March 23, 2012

This was grate for my thing,, thanks man for the valuable contribution,,

Rick
Sunday, March 25, 2012

Really straightforward and to the point. Thanks, good job!

Neil Carpenter
Sunday, April 1, 2012

Following your tutorial im getting an error message of undefined variable to $toemail … I can’t figure out why I’m getting this error message. Please help.

Frank Perez
Sunday, April 1, 2012

Please make sure that you have defined the variable $toemail as I did in the tutorial. That error message that you are receiving is actually a notice letting you know that the variable you are trying to use is not defined.

Sammi Walters
Tuesday, May 22, 2012

This is great, thank you. :) I’d love to use it but I’m also wondering how to make it so the success message is displayed underneath the form rather than the form fading out?

Sourabh
Monday, June 25, 2012

Hay Thanks, Its Simple and Effective :) Keep it up

Vibhor
Thursday, August 16, 2012

This is great, thank you. I am a student and i follow Quiz Plaza to get success. It is good to prepare.

Art
Tuesday, September 4, 2012

If I copy/paste the in an html page, instead of php, will it work?

easy Link building
Friday, December 7, 2012

hello there and thank you for your information – I have definitely picked up anything new from right here.
I did however expertise some technical issues using this web site, since I experienced
to reload the website a lot of times previous to I could get it to load properly.

I had been wondering if your web host is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my e-mail and could look out for a lot more of your respective intriguing content. Make sure you update this again soon.

liposom
Tuesday, January 8, 2013

I absolutely love your blog and find a lot of your post’s to be precisely what I’m looking
for. Does one offer guest writers to write content for yourself?
I wouldn’t mind composing a post or elaborating on some of the subjects you write related to here. Again, awesome website!

Bob
Monday, January 28, 2013

Hi there! I know this is kind of off topic but I
was wondering which blog platform are you using for
this website? I’m getting tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

Marcos
Wednesday, January 30, 2013

For some reason it works in localhost but not in production website. On the server, sends me to the process.php page after submit. Any idea why this happens. Thanks in advance for your help.

Frank Perez
Thursday, January 31, 2013

Seems like that would be related to a JavaScript issue. Are you seeing any JavaScript errors on the page that you are testing with? If you have any JavaScript errors before this portion of the script is able to run, it will cause the type of issue you are describing.

vacanzepolonia.com
Thursday, February 14, 2013

Hi there friends, fastidious paragraph and pleasant arguments commented here, I am
actually enjoying by these.

sai
Monday, February 25, 2013

Thanks nice tutorial.

energy efficient space heaters
Tuesday, February 26, 2013

I am genuinely glad to glance at this blog posts which
contains plenty of useful information, thanks for providing such
data.

Bob
Friday, March 1, 2013

Hi there,

You can find a nice demo with tutorial

http://www.mcwehbe.com/demo.php?imenu=4

Hope it would be useful

hablaameno.com
Tuesday, April 23, 2013

Amazing! Its really awesome piece of writing, I have got
much clear idea about from this article.

Dougie
Thursday, July 4, 2013

Would there be any reason this form wouldn’t work on an iPhone?? I put form on a friends website and she is saying it’s not working when all me testing shows a working form so the only thing I can think of is it has something to do with her iPhone?

ds
Friday, July 19, 2013

dsa

poker2
Sunday, July 21, 2013

казино елен или карточные игры пк бесплатно через торрент.

diet carbs
Tuesday, July 23, 2013

But, then as you have limited options for a no-carb breakfast
menu, you can contemplate these as breakfast choices.

aquaponics guide
Friday, July 26, 2013

Can you imagine that?

Lilia
Friday, August 2, 2013

Fat Loss four Idiots – How To Shed 9bls In 11 Days The very best
point that has ever occurred in the dieting and weight loss
globe has to be Fat loss 4 idiots.

Darren
Tuesday, September 17, 2013

Thank you soooo much! I’ve been trying for 9 hours with other people’s code to try and get a simple AJAX form to work, to no avail. Finally, I found yours and it worked right away, doing exactly what I needed with a little tweaking. Life saver!

Bhavik
Friday, September 27, 2013

thanks for sharing this post, it is awesome!!!

Mike
Friday, November 8, 2013

Thanks for this – simple and effective without all the extra bulk from other tutorials. Great job!

Satyam
Wednesday, June 18, 2014

can’t passing input box value and input file type image using Ajax, until now my code always return

asdf
Thursday, July 24, 2014

asdf

HOUSE OF HOLLAND lunettes de soleil
Monday, July 28, 2014

Good day! I know this is kinda off topic however , I’d figured I’d ask.

Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
My site discusses a lot of the same subjects as yours and I think we
could greatly benefit from each other. If you are interested feel free to shoot
me an email. I look forward to hearing from you!
Superb blog by the way!

338a
Wednesday, October 8, 2014

You can definitely see your skills in the work you write.
The sector hopes for even more passionate
writers such as you who are not afraid to mention how they believe.

Always go after your heart.

porova
Wednesday, October 22, 2014

ajax ajax forms AWS brush patterns css css dropdown menu css menu form validation Grunge Website high quality photos htaccess html html drop down menu html menu installing jquery jquery jquery attribute jquery effects jquery forms jquery hover jquery image hover jquery selectors jquery validation linux linux schedulers multi level css navigation parallels plesk photoshop effects photoshop patterns photoshop techniques PHP php and jquery remove background retro design rewrite urls rhcsa screen effect seo urls using jquery Web Crawler Web Harvesting Website Design Website Scrape WordPress WordPress Themes
Useful Links

A List Apart
BittBox
css Zen Garden
deviatART
Dreamstime
Frank Perez
Frank the Programmer
Icon Finder
themeforest

porova
Wednesday, October 22, 2014

Raca njerëzore ka bërë art për mijëra e mijëra vite. Këtu, në një listë kronologjike, gazeta britanike “Daily Telegraph” ka përzgjedhur 50 mrekullitë artistike të botës. Të parat vijnë skulpturat e Kafranit që ndodhen në muzeun e Kajros në Egjipt. Piktori Francis Beacon ka arritur në përfundimin se egjiptianët e lashtë ishin artistët më të mëdhenj. Asnjë vepër se përforcon këtë përfundim më mirë se skulptura e faraonit egjiptian me kokën e rrethuar nga perëndia skifter, Horus. Më pas janë skulpturat e Ashurbanipalit, ku Arti rrëfyes ka arriti një nivel të freskët natyralizmi në dekorimet e pallateve mbretërore asiriane. Në këtë linjë shquhen skulpturat që përshkruajnë gjuetinë e udhëheqësit Ashurbanipal. Aty portretizohet triumfi i mbretit ndaj luanëve. Ushtira e Terrakotës është një tjetër vepër arti masive në Kinë. Fotografitë s’mund ta shfaqin asnjëherë pamjen e plotë të ushtrisë së improvizuar. Duket sikur të vdekurit kanë dalë nga toka dhe po presin për komandën e radhës. Kjo ushtri është një takim me të shkuarën e largët e të shquar. Altari i Gentit në Belgjikë është një vepër tjetër që qëndron në piedestal. Duke përdorur shtresa ngjyre transparente, Jan can Eyck prodhoi një faksimile thuajse haluçinante strukture dhe sipërfaqeje në këtë altar. Xhevahiret, fijet e mjekrës dhe pendët e flatrave të engjëjve shfaqen në një mënyrë që edhe pas aq vitesh ngjan e mbinatyrshme. Po ashtu është dhe kopshti Zen në Japoni. Ky kopsht nuk përbëhet nga asgjë tjetër, përveç se me gurë të bardhë ranorë apo gurë myshku. Në terma perëndimore ky kopsht mund të përshkruhej si një instalacion skulpturor. Lista përbëhet nga vepra arti të njohura dhe shumë të njohura, por të gjitha kanë rëndësi të veçantë për kohën në të cilën janë bërë, cilësinë dhe specifikën e tyre.

website address
Friday, October 24, 2014

Its not mmy first tije to visit this website, i am browsing this web page dailly and obtain pleasant facts from
here all the time.

Leave a Comment



Need Help? Ask a Question

Ask anything you want from how to questions to debug. We're here to help.

You Must Be Logged In To Post A Question.

Log In or Register