Log In | Register | December 15, 2018


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">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="" tabindex="2" />
<label for="message">Message:</label>
<textarea cols="40" rows="8" name="message" id="message"></textarea>
<div id="loader">
<input type="submit" value="Submit" />

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:

$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">

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:

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

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">
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="loader.gif" /> Please Wait...');
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){

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


Wednesday, September 8, 2010

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

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.

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?


Frank Perez
Sunday, December 19, 2010

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

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


$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?

Friday, April 22, 2011

Very well explained thanx dude!

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(){

Any help would be greatly appreciated.


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.

Monday, October 17, 2011

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

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

Sunday, March 11, 2012

nice tutorial..

Friday, March 23, 2012

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

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?

Monday, June 25, 2012

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

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.

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.

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!

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.

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.

Thursday, February 14, 2013

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

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

Friday, March 1, 2013

Hi there,

You can find a nice demo with tutorial


Hope it would be useful

Tuesday, April 23, 2013

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

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?

Friday, July 19, 2013


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?

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.

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!

Friday, September 27, 2013

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

Friday, November 8, 2013

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

Wednesday, June 18, 2014

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

Thursday, July 24, 2014


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!

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.

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
css Zen Garden
Frank Perez
Frank the Programmer
Icon Finder

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.

Saturday, February 14, 2015

Our laboratory has taken and imported it.

Sunday, February 15, 2015

The greatest deer velvet extract has been taken by our laboratory
and imported it from New Zealand.

Monday, February 16, 2015

If some one needs to be updated with latest technologies afterward he must
be pay a visit this web page and be up to date daily.

Monday, February 16, 2015

Now add a why not check hhere ccup of coffee or tea. The results are found in spinach.
The most common name of the Himalayas as a result,
some of the healthiest tonic on the market today.

visit their website
Monday, February 16, 2015

With go to this website all this ccan have dry skin. People have claimeed
that the vegetable thatt comes to taste the best tasting juice, in addition to all of us have
to travel all the fine print. Itâ s been found in fruit slices or health bars.

Tuesday, June 30, 2015

są anemiczne sformułować sumę niezgód ślubnych, razem
spośród prywatnymi, jeśli sumują iż zacięcie się na
nie przysporzy im wskazaną pociechę. Stanowią straszliwie przebiegłe również jeśliby
owszem obecne mogę schwycić – surowe. W 4 casusach na 5 starannie zafascynowane sprawowaniem akcentuj do
skumulowanego dworu.

Heiß New Balance Lässig Rosa 574 Damen
Tuesday, August 4, 2015

I appreciate your wp design, exactly where did you download it from?

Monday, October 26, 2015


Saturday, February 27, 2016


Monday, June 20, 2016

現金網 http://king168.net

Wednesday, July 6, 2016


Friday, January 13, 2017

Stock Broker Database India

Monday, January 16, 2017

Have troubles with completing your assignment? Desperately looking for someone to do your homework? EssayErudite.com is the right place to opt for. Doing tons of writing has turned into a nightmare for many students. For many different reasons. In spite of the case, here at EssayErudite.com you will meet proven professionals in the field of writing assistance. Our mission is to make all those writing things as easy as possible for you.

Wednesday, January 18, 2017

Bonnie & Clyde – adult sex toys online shop! We offer wide range of sex products and adult toys for him, her and couples.
Spice up your sex life. Shop today.

Thursday, January 26, 2017

Bonnie & Clyde Toys – adult sex toys online shop! We offer wide range of sex products and adult toys for him, her and couples.
Spice up your sex life. Shop today.

Tuesday, February 7, 2017

xcdex 軟體網http://interior-plan.com/

Tuesday, February 7, 2017

http://xcdex.com.tw/ xcdex 軟體網

best retractable baby gate
Tuesday, February 7, 2017

Aiɗ style (DPNA) Autonomouѕ traveⅼer along with an intellectual disability that may answeг & understand to safety guidelines that requirеs
help via the airport terminal (retirеment & landing) to thᥱ boarding gate.

Tuesday, February 7, 2017

I just wanna say hi to you all

Sunday, February 26, 2017

Hello. All that you want to know about chicken.

Sign. =)

Wednesday, March 1, 2017

xcdex 軟體網http://interior-plan.com/

Monday, March 6, 2017

Как ногти укрепить в домашних условиях? Поделитесь советом.

Tuesday, March 14, 2017

桃園居酒屋 http://yakitori-izakaya.com/

Friday, March 24, 2017

referenceur a grenoble
un bon référenceur passe par les bonnes techniques de référencement
c’est pour cela que vous pouvez visité mon site en toute confiance

Monday, March 27, 2017

Алюминиевый реечный потолок БАРД Нижний Новгород

Tuesday, August 1, 2017

XYZ專業光碟教學網站 http://xyz.net.tw/

Monday, August 7, 2017

Learn how to make money on Youtube. In this FREE Ebook you will learn how to make a living on Youtube like thousands of other people do every day.
Here’s what this 58 page step by step guide will teach you:

Different methods that I use to generate income on Youtube.
The most powerful methods on how to rank your Youtube videos on the #1 Spot.
How to use affiliate networks which can pay upwards of 50$ per sale.
How to use cheap services to outsource all of the hard work! https://goo.gl/MxVgMs

aryan cruze
Friday, August 11, 2017

hello,nice article well explained ,apart from this how do i disable browser submitting duplicate data
after refreshing the page..thanks

aryan cruze
Friday, August 11, 2017

your comment section is also jumping back to top after 1st submit how to be at same position after submitting form data..can u help me out sir,,

Tuesday, September 5, 2017


Sunday, September 24, 2017



Wednesday, December 13, 2017

Добрый день. Интересует ваша продукция, хотел сделать заказ…..
Как бы хотелось чаще получать такие письма. Но на практике из 100 посетителей сайта только 2 – 5 оставляют заявку в обратной связи, остальные 95 человек просто уходят к вашим конкурентам.
С нашим сервисом Вы получите информацию о 40 посетителях сайта из 100 (телефон, e-mail, профили соц. сетей), узнаете что конкретно их интересовало и сможете дать предложение, от которого они не смогут отказаться.
Это не Seo продвижение, не Я.Директ и не таргетинг реклама (все это немного устарело). Рост продаж при применении нашего сервиса – в среднем 15%. Гарантию окупаемости наших услуг в 10 раз прописываем в договоре.
Есть бесплатная демо-версия (получите 10 e-mail, 5 телефонов и 10 профилей соц. сетей посетителей вашего сайта). Более подробно на сайте https://goo.gl/sc9bUA
P.S. При обращении до 20 декабря бесплатная CRM система в подарок.

Saturday, March 17, 2018



Monday, March 19, 2018

perhaps the buses to england https://przewozydoanglii.pl

Hallo People
Thursday, March 22, 2018



Sunday, June 24, 2018

My up to date network project:

Friday, July 20, 2018

Assignment recto moved:

Friday, September 14, 2018

best buses I ever used to http://busydoanglii24.pl

Saturday, September 15, 2018

Каждому Привет! Заходите на .

Monday, October 15, 2018


Friday, October 19, 2018


Wednesday, October 31, 2018

the king casino online game : https://custory.com/theking/

Wednesday, October 31, 2018

woori casino online game homepage : https://custory.com/woori/

Wednesday, October 31, 2018

super casino online homepage : https://custory.com/super/

Wednesday, October 31, 2018

woori casino online game homepage : https://como79.com/

Wednesday, October 31, 2018

the king casino online homepage : https://como79.com/theking/

Wednesday, October 31, 2018

super casino online game homepage : https://como79.com/super/

Wednesday, October 31, 2018

woori casino online homepage : https://stylebet77.com/

Wednesday, October 31, 2018

the king casino online homepage : https://stylebet77.com/theking/

Wednesday, October 31, 2018

the king casino homepage : https://dancesweb.com/theking/

Wednesday, October 31, 2018

woori casino online homepage : https://dancesweb.com/woori/

Wednesday, October 31, 2018

super casino online homepage : https://dancesweb.com/

Wednesday, October 31, 2018

the king casino online game : https://pauio.com/theking/

Wednesday, October 31, 2018

woori casino online : https://pauio.com/woori/

Wednesday, October 31, 2018

super casino online homepage : https://pauio.com/super/

Tuesday, November 6, 2018

Заработок на партнерских прогах, на покупках других людей, пассивный заработок, обзоры проектов, хайпов, инвестпроектов и. д. ссылка: http://rabotarabotay.blogspot.com/

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