Submit A Form Without Page Refresh using jQuery
In Javascript / AJAX by EricPreviously on NETTUTS, Philo showed how you can use jQuery to add form validation to wordpress comments that works without any page reload. Another great way of utlizing jQuery to enhance user experience is to not just validate, but to submit your form entirely without a page refresh. In this tutorial I'll show you how easy it is to do just that -- submit a contact form that sends an email, without page refresh using jQuery! (The actual email is sent with a php script that processes in the background). Let's get started.
The Demo
In this example, we have a simple contact form with name, email, and phone number. The form submits all the fields to a php script without page refresh, using native jQuery functions (native meaning, you don't need to download any extra plugins to make it work.
If you have found this article without any prior familiarity with jQuery, a great place to get started would be Jeffrey Way's article on 15 Resources to get you Started with jQuery From Scratch.
Step 1 -Build the HTML form
Let's take a look at our html markup. We begin with our basic html form:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label class="error" for="email" id="email_error">This field is required.</label>
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label class="error" for="phone" id="phone_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
You might notice that I have included a div with id contact_form that wraps around the entire form. Be sure to not miss that div in your own form as we will be needing this wrapper div later on. You might also notice that I have left both the action and the method parts of the form tag blank. We actually don't need either of these here, because jQuery takes care of it all later on.
Another important thing to be sure to include is the id values for each input field. The id values are what your jQuery script will be looking for to process the form with.
I've added some css styles and a background image in Photoshop to produce the following form:

Step 2 - Begin adding jQuery
The next step in the process is to add some jQuery code. I'm going to assume that you have downloaded jQuery, uploaded to your server, and are referencing it in your webpage.
Next, open up another new javascript file, reference it in your html as you would any normal javascript file, and add the following:
$(function() {
$(".button").click(function() {
// validate and process form here
});
});
What the first function() does is, it loads the events inside, as soon as the html document is ready. If you have done any work in jQuery previously, the function is the same as jQuery's document.ready function. So we start with that, and inside we have our click function that executes on clicking the submit button with class name of "button". Ultimately what we have accomplished with these lines of code is the same as if we were to add an onclick event to the submit button in the html. The reason we do it with jQuery is for clean separation of our presentation from our scripts.
Step 3 - Write some form validation
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
});
});
Inside our function that loads when the page is ready, we add some form validation. But the first thing you see that got added is $('.error').hide();. What this does is hides our 3 labels with class name "error". We want these labels to be hidden not just when the page first loads, but also when you click submit, in case one of the messages was shown to the user previously. Each error message should only appear if validation doesn't work out.
We validate by first checking if the name field was left blank by the user, and if it is, we then show the label with id of name_error. We then place the focus on the name input field, in case the user is at all confused about what to do next! (I have learned to never assume too much when it comes to form users).
To explain in more detail how we are making this happen, we set a variable 'name' to the value of the input field with id "name" -- all with one line of jQuery:
var name = $("input#name").val();
We then check if that value is blank, and if it is, we use jQuery's show() method to show the label with id "name_error":
if (name == "") {
$("label#name_error").show();
}
Next, we place the form focus back on the input field with id of "name", and finally return false:
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
Be sure to have return false in your code, otherwise the whole form gets submitted (which defeats the purpose of this tutorial)! What return false does is it prevents the user from proceeding any further without filling out the required field(s).
Step 4 - Process our form submission with jQuery's ajax function
Now we get to the heart of the tutorial -- submitting our form without page refresh, which sends the form values to a php a script in the background. Let's take a look at all the code first, then I will break down into more detail next. Add the following code just below the validation snippet we added previously (and before the button click function is closed out):
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
We have a lot going on here! Let's break it all down - it's so simple and so easy to use once you understand the process. We first create a string of values, which are all the form values that we want to pass along to the script that sends the email.
Recall previously, we had set a variable 'name' with the value of the input field with id "name", like so:
var name = $("input#name").val();
We can use that 'name' value again, as well as the 'email' and the 'phone' values, to create our dataString:
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
I've commented out an alert that I sometimes use to be sure I am grabbing the right values, which you may find helpful in the process. If you uncomment that alert and test your form, assuming everything has gone right so far, you should get a message similar to the following:

Now we get to our main ajax function, the star of today's show. This is where all the action happens, so pay close attention!
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
//display message back to user here
}
});
return false;
Basically what's going on in the code is this: The .ajax() function processes the values from our string called dataString (data:dataString) with a php script called process.php (url:"bin/process.php"), using the 'POST' method (type:"POST"). If our script processed successfuly, we can then display a message back to the user, and finally return false so the page does not reload. That's it! The entire process is handled right there in these few lines!
There are more advanced things you can do here, other than sending an email and giving a success message. For example you could send your values to a database, process them, then display the results back to the user. So if you posted a poll to users, you could process their vote, then return the voting results, all without any page refresh required.
Let's summarize what happened in our example, to be sure we have covered everything. We grabbed our form values with jQuery, and then placed those into a string like this:
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
Then we used jQuery's ajax function to process the values in the dataString. After that process finishes successfully, we display a message back to the user and add return false so that our page does not refresh:
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
The success part of the script has been filled in with some specific content that can be displayed back to the user. But as far as our ajax functionality goes, that's all there is to it. For more options and settings be sure to check out jQuery's documentation on the ajax function. The example here is one of the simpler implementations, but even so, it is very powerful as you can see.
Step 5 - Display a message back to the user
Let's briefly look at the part of the code that displays our message back to the user, to finish out the tutorial.
First, we change the entire contents of the contact_form div (remember I said we would be needing that div) with the following line:
$('#contact_form').html("<div id='message'></div>");
What that has done is replaced all the content inside the contact_form div, using jQuery's html() function. So instead of a form, we now just have a new div inside, with id of 'message'. Next, we fill that div with an actual message -- an h2 saying "Contact Form Submitted":
$('#message').html("<h2>Contact Form Submitted!</h2>")
We next add even more content to the message div with jQuery's append() function, and to top everything off we add a cool effect by hiding the message div with the jQuery hide() function, then fade it all in with the fadeIn() function:
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
So the user ends up seeing the following after they submit the form:

By now, I think you will have to agree that it is incredibly easy to submit forms without page refresh using jQuery's powerful ajax function. Just get the values in your javascript file, process them with the ajax function and return false, and you are good to go. You can process the values in your php script just like you would any other php file, the only difference being that the user does not have to wait for a page refresh - it all happens silently in the background.
So if you have a contact form on your website, a login form, or even more advanced forms that process values through a database and retrieve results back, you can do it all easily and efficiently, and perhaps most importantly, you enhance the end user experience with your website by providing interactivity without their having to wait for the page to reload.
Demo & Source
I would like to add some final words about the demo example provided. In the demo, you may notice that there is in fact one plugin being used - the runonload.js file. I did state at the beginning of the tutorial that we would not be using any plugins, and then you find in the demo there is an extra runonload script, so some explanation may be necessary!
The only use I made with runonload actually has nothing to do with processing the form. So you can accomplish the ajax functions completely without any extra plugins. I only used runonload to focus the name input field on page load. It has been my experience that calling runonload can sometimes be a better replacement for jQuery's native document ready function, and I found that to be the case while putting together this tutorial. For some reason the focus() function would not work on page load using jQuery's native document ready function -- but it did work with runonload, and that is why you find it as part of the example. So if you know of a way to accomplish that without using runonload I would be happy to hear from you about that.
Comments
Leave a CommentAdd a Comment














Andrei Constantin
July 24th, 2008
Very nice, thanks a lot.
I’m gonna give it a go
sanjay
July 24th, 2008
the demo looks very good.
I will try it today along with my PHP form processor….
Thx and cheers,
Sanjay
The Frosty
July 24th, 2008
Thats cool, I have used plugins for wordress a lot, but I do enjoy a good read!
aNieto2k
July 24th, 2008
var name = $("input#name").val();var email = $("input#email").val();
var phone = $("input#phone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
is the same than
$("#contact_form form").serialize();
Good tutorial.
insic
July 24th, 2008
good one. i am using a this technique a lot.
KAZI
July 24th, 2008
Nice work, but i think you missed to check your styles, the submit button is not shown properly in IE 7
Neil Berrow
July 25th, 2008
Exactly what I’ve been looking for I can’t thank you enough! Love the site, I wait impatiently for every new addition!
Imzyos
July 25th, 2008
var dataString = ‘name=’+ name + ‘&email=’ + email + ‘&phone=’ + phone;
VS
$(”form”).serialize();
Peter
July 25th, 2008
Very nice, but I have two problems with your solution, one technical and one fundamental:
* There is nothing to indicate the data is being submitted to the server while waiting for the reply. The submit button should be disabled while waiting for the Ajax return, else you will allow the form to be submitted several times.
* This solution will not work without JavaScript. You may say that everyone that matters has enabled JavaScript in their browser, but more and more people are browsing internet on their phones, PDA’s, webtops, game consoles, MP3 players, etc, and then you just cannot count on stable JavaScript support.
Mark Bowen
July 25th, 2008
Hiya,
There are some very nice tutorials on here of late but it would be really nice if the Javascript versions worked without Javascript enabled too. Shouldn’t be too hard to do but I’m just thinking that if people do come to your site without Javascript enabled then the form isn’t going to operate correctly for them. Just a thought though.
Nice tutorial anyway though.
Best wishes,
Mark
Ben Griffiths
July 25th, 2008
Nice and simple, and does exactly what is needed an no more, perfect
Thanks!
@Mark Bowen - the action on this form is set to nothing, so if there was no JS enabled it would submit to itself. It’s easy to pop some PHP in the top of the page checking for a submission and then processing the form if needed, including showing error messages.
Guillaume
July 25th, 2008
Nice tutorial. I’m just thinking about using this script for posting comments on my blog, but then I’ll get some SEO issues if comments are called through Ajax.
Using it for contact forms is very nice though
Niall
July 25th, 2008
guillaume: why not just use this form method to put the comments into your database, and then use a non-ajax system such as php to display them. That shouldn’t give any SEO issues should it?
Great tutorial!
James
July 25th, 2008
Hey, nice tutorial. Personally I’d do all the validation on the server side, this saves you from doing it twice (client AND server side). You can also use jQuery’s serialize function (http://docs.jquery.com/Ajax/serialize) to process all the form inputs for sending data to a server. This way if you add more form fields the javascript will be able to cope without modification.
James
davidinbcn
July 25th, 2008
disable the submit button when u submit…
roger
July 25th, 2008
need to add in some ../ into the css file so the images in the css are at the right level as is it doesnt show the images!
Thanks for the tutorial contact forms have always been a headache for me!
David
July 25th, 2008
Nice tutorial - I agree with Mark though that for users without JS enabled, it’d be great to present an alternative. I went to a presentation by Jeremy Keith (adactio.com) where he talks about his HIJAX method of using ajax which basically intercepts the form details IF javascript is present, and if it isn’t, processes the form in the normal way.
That’s not to take anything away from this great tutorial or this wonderful site - keep up the good work!
David
Shane
July 25th, 2008
Nice tutorial. My only (small) comment is that I’d prefer to see all fields failing validation to be shown at once, rather than one at a time.
That’s a small niggle and one that’s easily fixed.
Thanks for posting the tutorial.
Daniel
July 25th, 2008
nice tutorial, very useful! thanks a lot.
Alex
July 25th, 2008
What is missingin this nice demo is the ajax_loading gif that will notice the user that the action is ongoing, rather than nothing, with peep clicking like crazy on the sending button.
very nice and i’m going to use this a lot!
Jake G.
July 25th, 2008
Very Nice Tutorial. I am going to use this tonight on my personal website.
Thanks!
Rijalul Fikri
July 25th, 2008
This what I looking for, thx’s
Michael Thompson
July 25th, 2008
I take it we’re above progressive enhancement, eh? A form without an action and the validation event attached to the submit button’s click?
These are dangerous practices to be teaching in a tutorial.
Andrejs
July 25th, 2008
It is very useful script.
Thanks a lot.
Nate
July 25th, 2008
This will come in very handy. Thanks
Mike Busch
July 25th, 2008
I have to agree with Michael Thompson. Using AJAX to submit the form is great, but doing it without a non-javascript fallback is terrible practice (and means that non-JS users can’t contact you… which could cost you or your client money).
If you really want to do it right check out the jQuery Form Plugin. Its based entirely around progressive enhancement, and gives you callbacks for beforeSubmit (for validation), success, error, etc.
Disclaimer: I am not affiliated with the above plugin, but I’ve used it extensively on projects for Enterprise Level clients.
Ben Griffiths
July 25th, 2008
@Michael Thompson
A form without an action will post to itself - nothing wrong with that… especially as this is a demo so the form isn’t getting posted anyhow. Whats wrong with validating with the submit button’s on click?
kiran voleti
July 25th, 2008
This is good one.
Thanks
http://www.toputop.com
dlv
July 25th, 2008
really nice, thanks again
i’ve checked it all…i’m in holidays so when i come back i’m goint to run my hands
adeux!
Snorri3D
July 25th, 2008
realy nice tut and thank alot.
BUT! when i use opera and i click the submit button fast five times then in the confirm page i get five green circles with V in it in sted of one just saying but i dont know if this is a error or not
but thank a lot for the tut again
Steve
July 25th, 2008
nice tut. again, u should always make a complete tutorial about taking care when JS isnt enabled too though.
Barndizzle
July 25th, 2008
I experienced the same issue as Snorri3D. I think it would be simple fix to deactivate the submit button after it is clicked. Details….nice tutorial.
raj dash
July 25th, 2008
Keep in mind that is more a demonstration of technique, not a live, working application. Trapping for the condition of JS not being on is something that can always be added later.
LOL at Snorri3D. Sounds like something that’s going to happen a lot
Dan
July 25th, 2008
Useful
Al
July 25th, 2008
What if I want to have submitters also upload a file. How would that work?
Dave McFarland
July 25th, 2008
@ben griffiths
The click event on the submit button isn’t the only way a form can be submitted. Hitting the Enter key while in a text field also submits a form. It’s best to do form validation as well as the AJAX post on the form’s submit event.
Taylor Satula
July 25th, 2008
Very cool, looks good too!
crysfel
July 25th, 2008
thats ok, but…. what if an error occur on the server?? what if the MSG never send?? the confirmation message should be return by the server!!
have funnnnn
Monkeytail
July 25th, 2008
Sieht gut aus.. nice tut!
question:
what’s the difference between html() and append() function?
from code:
$(’#message’).html(”Contact Form Submitted!”).append(”We will be in touch soon.”)
.. why first html() and then append() and not twice html or append
Mr. Haynes
July 25th, 2008
I have been waiting for this for a long time!!!!
Braden Keith
July 25th, 2008
Looks fine, looks like it works great. I like the not having to refresh. And crysfel has a good point.
Andrew
July 25th, 2008
Another nice tut! Gotta love that AJAX!
Braden Keith
July 25th, 2008
BTW Collis!
I got a wordpress blog now! I got it for ha.xors.org which will be my personal blogging site, so keep them wordpress tuts coming
James
July 25th, 2008
hmmm, I like the tutorial overall, but I have some issues with some stuff:
Firstly, you shouldn’t be attaching the ajax to the click event of the button, you should be attaching it to the submit (”onsubmit”) event of the form. Also, that green-tick image should be preloaded. Also, don’t use underscores in your ID names - older browsers don’t like this. And what is the point in appending the “we’ll be in touch soon” message if ur just gonna hide it a split second later- it doesn’t even appear for the user to read it! The worst thing about this tutorial is that it does not degrade!!! - This is a big issue!
@David - You don’t need an entirely different method/framework/technology (hijax) in order to make the enhancement unobtrusive.
Philsbury
July 26th, 2008
Shane mentioned he’d like the validation show at once. If you use jQuery’s jquery.validate plugin you get that to happen. I’t also far fewer lines of code! Otherwise very nice tutorial
Josh Riddle
July 26th, 2008
Great tutorial as always. In case anyone decides to go the plugin route there is an excellent Form Plugin for jQuery that I have found to be a great resource if you are going to be using this method for a lot of pages on your site:
http://malsup.com/jquery/form/
Matrich
July 26th, 2008
Thanks so much for this great tutorial. I am hoping that one day I will adopt jQuery and this will be very useful.
I need some help to understand how someone can use jQuery such that when the page is submitted, it is validated and then the person can be redirected to another page e.g. wen someone is trying to login, I can validate the empty fields, check and validate the credentials and then someone is directed to another page instead of just replacing content in a div. I already have the scripts running though I have still failed to understand how to use jQuery in this respect.
I will be very grateful for the help and thanks for the great tutorials you are posting.
Trevor Davis
July 26th, 2008
I have written a similar article, AJAX Forms with jQuery that discusses creating a form that works with or without JavaScript.
A couple of things that I suggest is to instead of having the error messages already present in the markup on the page, just append them with JavaScript. Also, I think a more descriptive error message would be better. Instead of saying “This field is required”, provide a better error message. Like, “You forgot to enter your email address” or “Your email address is invalid”. Just my thoughts.
Joefrey Mahusay
July 26th, 2008
Thanks for this, It’s nice and simple.
Mark Abucayon
July 26th, 2008
I love it very lovely flow right there thank you for sharing this one.
Eric
July 28th, 2008
Hey everyone! Thanks for all the gracious comments regarding the tutorial. It’s just so easy to submit forms with jQuery and ajax so you don’t get a page refresh. The possibilities seem limitless and I’m glad if I can help others get started with these techniques.
Some of you have mentioned what is lacking in the tutorial, namely lack of support for users without javascript. I think you guys are absolutely right to mention that problem, and I definitely recommend taking care on this issue when you publish this kind of form to a live site. I would probably go with Ben Griffiths’ solution to put a php script in the contact page itself which checks for form submission and processes it if so.
I see a couple recommendations for the Malsup form plugin - I have yet to give that one a try! Looks like it handles precisely these issues being discussed.
Also thanks to James for mentioning not to put underscores in your ID names due to problems with older browsers not recognizing those.
@Monkeytail - the html() function replaces whatever is inside the current div. The append() function does not replace anything, instead it adds on to the end whatever you currently have inside the div.
@Matrich - have you considered just using window.location to redirect a user to another page? Perhaps you could place that within the success part of the ajax function.
Dwayne
July 28th, 2008
Mine did not work I do not know what I am doing wrong
joelrthomas
July 29th, 2008
This is a very nice tutorial, the end result is incrediblly useful. I am wondering if someone could help me figure out how to integrate this with my existing forms. I have them posing to a .jsp page and my fields also have different names such as “Contact0FirstName” as apposed to “name”.
Any help would be greatly appreciated, thanks!
Fox
July 30th, 2008
Awesome. It’s very useful.
jesusvld
July 31st, 2008
Excellent! nice work!
Ashok.p
August 4th, 2008
hi , am ashok i need the code in javascript rather than in PHP. plz send me the code in javascript
Maicon
August 5th, 2008
Great work! I learned a lot!
ebot
August 5th, 2008
nice tuts!!!
Janpeter
August 5th, 2008
In the readme.txt you are talking about some chances i have to make to get it work. In process.php i have to change $to, $email, $fromaddress, and $mail->From. I don’t know what information I have to put here. I’m a noob sorry:).
$to = ’someone@example.com’;
$email = ‘email@example.com’;
$fromaddress = “you@example.com”;
$mail->From = “mail@yourdomain.com”;
I chance it al to info@slagersworst.de but it isn’t working…
mattems
August 11th, 2008
awesome.
and now how do we get that into wordpress as a plugin
great work!
TravelScoot
August 13th, 2008
That’s cool, check out this mobility scooter I bought my mom for Christmas.
http://www.travelscoot.com
It is called TravelScoot mobility scooter and it folds up like an umbrella and weighs just 35 lbs. She keeps it in a carrying bag in her trunk. She takes it out anywhere.
allmoney.ws
August 14th, 2008
It’s is not very good form - user don’t see progress bar when he click on button
ralph
August 19th, 2008
very informative
md5
August 21st, 2008
Bad. In demo email fileld not check. I write ‘testtest.com’ (not ‘test@test.com) and form was submit succes. 2author: if you create a tutorial for noobs do it as professional.
// sorry for my English - I am from Ukraine and my English is bad.
Alberto
August 23rd, 2008
Great tutorial, thanks! How do I integrate some radio button values and check boxes into the form and have them emailed as well? I’m kind of new to PHP and javascript and can’t seem to find a good tutorial on how to get that part of my form working.
Coder
September 1st, 2008
1. Does not check for valid email address
2. Phone field allows you to Input a number
Ben
September 4th, 2008
Awesome tutorial, very descriptive, step by step guide as to whats going on, all thats left is to see if it works!!
Ciel
September 5th, 2008
Have a question.
How can I put a simple iteration if-else in the returned messege?
For exaple, if my process.php does a control in a registration form - maybe for an already existing registered user - how can it comunicates this information to the ajax function and then change the returned messege?
Sorry for the bad English, I’m Italian