I am a Web Developer based in Michigan and I specialize in User Interface Design and Development.  I create functional, aesthetic and user-friendly web applications that adhere to the latest web standards. 

I am currently available for new projects, so hire me!

 

How To Submit a Form with jQuery and AJAX

June 1st 2011

HTML forms make up a large part of the web. They are the primary method for retrieving input from users.  Typically, you fill out the form, click the submit button, and be redirected to a thank you page.  For web applications, this may not be ideal - you may not want the user to leave the page. In this article, I'll show you how to use jQuery's AJAX function to submit a form asynchronously to the server and avoid a redirect.

A Simple Contact Form

Here's an example of a simple contact form (fyi: submitting it won't do anything yet). We'll be submitting this form via AJAX with jQuery.

Your Name:
Your Email:
Your Message:


 

Here's the code for the form:

<form id="ContactForm">
    Your Name: <input type="text" name="name" value="" /><br /> 
    Your Email: <input type="text" name="email" value="" /><br /> 
    Your Message:<br /> <textarea style="width: 200px; height: 100px;" name="message"></textarea> 
    <br /><br /> 
    <input type="submit" name="submit" value="Submit" /><br />
    <div class="form_result"> </div>
</form>

Notice that I gave my form tag an ID of "ContactForm". We'll need this later so that jQuery can find and retrieve all the data contained in the form. Additionally, I've included a div element to which we will dynamically update with the response from the server.  The div has a class of 'form_result' that we can use to tell jQuery where the response from the server should be output to.  The reason I'm using a class identifier here instead of giving the div an id attribute is because on very large forms, you may want the result of the form to be shown at the very top of the form as well as the bottom.  With jQuery, we can select and update multiple elements with the same class.  However, we can only update one element with the same id.  

jQuery's AJAX Function

The syntax for jQuery's ajax function looks like this:

jQuery.ajax(url, [settings]);

A complete reference to this function can be found by clicking on this link:jQuery's AJAX function. There are numerous settings available to use with this function, but we're only going to be using a handful. We'll discuss each setting briefly here: 

  • url: set this to the URL the form will be submitted to (you'll probably want to put in the URL to your form handler). We'll be setting ours to jQuery-ajax-demo.php for demonstration purposes.
  • type: this is the method type for the form; set it to POST or GET. In our case, we'll be using POST.
  • data: this is the data you'll be submitting; it's a standard query string that you typically see after a domain name in the browser's address bar. You'll see that for the most part, jQuery will create the query string for us.
  • success: you can set this to a single callback function, or as of jQuery 1.5 - an array of functions. We'll be setting ours to a single callback function that accepts the response from the server (first parameter of the callback function).

Let's see what a call to jQuery's AJAX function would look like for our demo:

$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#ContactForm').serialize(), success: function(response) {
    $('#ContactForm').find('.form_result').html(response);
}});

As you can see, we are setting the 'type', 'url', 'data', and 'success' settings of jQuery's AJAX function. In the 'data' setting, we're using jQuery's serialize() function by supplying the id of the form as the context.

jQuery's serialize() function looks at every field in the supplied context and creates a string of key-value pairs. The 'name' attribute of each of the fields in the form are used as the keys while the actual data contained in the fields become the values. So for example, in the form we created above, our query string (the result of the serialize function) might look like this:

name=Jason&email=me%40example.com&message=hey+what's+up%3F

That's if I submitted the form with Name set to "Jason", Email set to "me@example.com", and Message set to "hey what's up?". The serialize() method also encodes the data so it can be easily transmitted to the server. 

We now have everything we need to submit the form to the server, but we do not have a form handler yet that will intercept the data and do something with it.  

A Simple Form Handler in PHP

Doing anything too fancy is outside the scope of this article, so we're just going to create a simple form handler that intercepts our data and outputs the data as the response.  Take a look at this PHP code:

if(isset($_POST['name'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $msg = $_POST['message'];
	
    ?>
    Your Name Is: <?php echo $name; ?><br />
    Your Email Is: <?php echo $email; ?><br />
    Your Message Is: <?php echo $msg; ?><br />
    <?php
    die();
}

Here we are first checking to see if the form was submitted. The result of isset($_POST['name']) will be true if the key 'name' is defined in PHP's $_POST array, and false otherwise. It will be since 'name' is one of the fields on the form that is serialized and submitted via the AJAX request. Next, we retrieve and then output the data from each of the fields: name, email and message. I told you it was simple! In reality though, you'd probably want to validate the data. Although validating data from a form submission is outside the scope of this article, it does give me an idea for an article I could write next!

Putting It All Together

We have everything we need now, we just have to put it all together! The first thing we will do is create a JavaScript function we can call that runs our jQuery AJAX code, here's what that looks like:

function submitForm() {
    $.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#ContactForm').serialize(), success: function(response) {
        $('#ContactForm').find('.form_result').html(response);
    }});

    return false;
}

You can see we return false from the function. This is very important! When we return false from this function, it will stop the browser from submitting the form and reloading the page or redirecting us. The last we have to do is update the code for our form to call our submitForm() function:

<form id="ContactForm" onsubmit="return submitForm();">
    Your Name: <input type="text" name="name" value="" /><br /> 
    Your Email: <input type="text" name="email" value="" /><br /> 
    Your Message:<br /> <textarea style="width: 200px; height: 100px;" name="message"></textarea> 
    <br /><br /> 
    <input type="submit" name="submit" value="Submit" /><br />
    <div class="form_result"> </div>
</form>

Check out the demonstration by clicking on Demonstration on How To Submit a Form with jQuery and AJAX.  


Discussion


Mr. Raymon
06/01/2011
Mr. Raymon
I apologize for the stupid message "werrewt", user "wret". I was testing the form contact in working.

Thanks for the tutorial ;)
MJ
06/02/2011
MJ
A form element should have "action" and "method" attributes to be standards compliant.

I usually leave these blank and use

$('#ContactForm').click(function (e) {
e.preventDefault();
$.ajax( /*AJAX Code*/ );
});
MJ
06/02/2011
MJ
Correction:



$('#Submit').click(function (e) {
e.preventDefault();
$.ajax( /*AJAX Code*/ );
});
Jason T. Stiles
06/02/2011
Jason T. Stiles
@MJ - Yep, you could do it that way too. You could also attach a submit event to the form handler as well:

$('#ContactForm').submit(function() { /* AJAX Code */ return false; });

When doing it this way, just make sure you return false from the function, otherwise it won't work.
Israel
06/02/2011
Israel
And if I send data and files in the same form
Jeff
11/18/2011
Jeff
Great explanation and examples... thank you!!!!
joshua
02/01/2012
joshua
Thanks for this tutorial. I believe I found a slight bug - you are missing a closing brace in the ajax code sample following the line "Let's see what a call to jQuery's AJAX function would look like for our demo:" - The top line has two opening braces and you only close one of them before the parentheses at the end.
Jason T. Stiles
02/01/2012
Jason T. Stiles
@joshua - thank you! I have fixed it. :)
rajr
02/16/2012
rajr
Very nice, thanks for putting this together for those of us on the learning curve.
Terry Lawton
03/02/2012
Terry Lawton
Fantastic post. Hereâs a tool that lets you build all types of web forms with email alerts fast and without coding. Just point and click http://www.caspio.com/online-database/features/web-forms-online.aspx
vikas
03/03/2012
vikas
Thanks for submit this type of article.
Peter
03/10/2012
Peter
Hi, and sorry for my bad english :)
Im beginner in web developing, and i have question why, when i copy source code from "Demonstration on How To Submit a Form with jQuery and AJAX" to my computer and save as "jquery-ajax-demo.php", then jQuery Ajax post method not work in my PC.
Thank you :)
jeremy
03/13/2012
jeremy
This post is excellent. The best I've seen on the topic.

If you remove the " ('#ContactForm').find " you can put the element wherever you want. It is an unnecessary DOM query.
jeremy
03/13/2012
jeremy
This post is excellent. The best I've seen on the topic.

If you remove the ('#ContactForm').find you can put the div class="form_result" element wherever you want. It is an unnecessary DOM query.

Hmm weird escape behavior ; )
Lionel
03/22/2012
Lionel
This is the best tutorial i have seen so far when it comes to submitting a form without refreshing the page... nice one. But I have a question, is there a way one can fade in the message from the php file instead of just displaying, would really be nice. Thanks
Jason T. Stiles
03/22/2012
Jason T. Stiles
@Peter - There could be a number of reasons. Do you have a local webserver setup for it?

@jeremy - I added the #ContactForm because in many cases, I have several forms on a page. So if I did not have this additional specificity, I would risk updating other form results unnecessarily and confusing my User. :)

@Lionel - Yes, jQuery has fadeIn() and fadeOut() methods that can do just that. Basically, you would use fadeOut() on the form result, apply the changes to the html, and then call fadeIn(). You must be careful in how this is used though. Both fadeIn() and fadeOut() take a callback function as their second argument. Using the callback, you can make sure the fadeIn happens before the fadeOut. Something like this: $('#ContactForm').find('.form_result').fadeOut(function() { $(this).html(response).fadeIn(); }).
student
03/30/2012
student
thank you!!!!
Jacob
04/04/2012
Jacob
what if I wanted to integrate this into a jQuery modal window..
Jason T. Stiles
04/04/2012
Jason T. Stiles
@Jacob - you have a couple options: place the form in a hidden container (div) and then load the modal window with the appropriate selector for that div, or you could load the form's html with AJAX and create the modal from it.
Jacob
04/04/2012
Jacob
Thank you for the quick response! I have succeeded in putting it into a modal window, but when I submit the form it posts the whole form again instead of just the POST variables.
Jason T. Stiles
04/04/2012
Jason T. Stiles
@Jacob - I am not sure what you mean by "it posts the whole form again instead of just the POST variables". Can you give me more details? When using the jQuery serialize() method, all fields contained in the form selector are posted to the URL you specify.
Jacob
04/04/2012
Jacob
(Stand alone not in jquery Modal or anything) When I feel out the form and hit submit, instead of just displaying beneath the form the values I had entered (i.e. our Name Is: jacob
Your Email Is: jacob.buck@gmail.com
Your Message Is: sadasdfasfds)

It displays the whole form again THEN the values. Hope that makes sense.
Jason T. Stiles
04/04/2012
Jason T. Stiles
@Jacob - are you submitting the form to the same page that contains the form? If you are, and you aren't handling the case of displaying the form or not when a form is submitted to it, then you would see the form again along with the values. If you are submitting to the same page, you will need to check first if the values have been submitted: if they haven't been submitted, output the form, otherwise output the values (and not the form). You can check if a value is submitted with PHP's isset() function as shown in my blog post.

It could also simply be that you aren't returning (or exiting with php's die() function) before the form is output. I sent you an email if you need further help.
How can I make output outside form ContactForm? I tried to make an output outside form but failed. Thanks in advance.
Mothi
04/10/2012
Mothi
Instead of putting output in a div, i need to insert form data into mysql and submit the form in action URL. can u pls advice me?
Lucia Hustatyova
05/02/2012
Lucia Hustatyova
Hello,
I have the same problem as Jacob - when I submit the form, i see again whole form and then values. I try to submit form to the same page. I have also isset() function... My code:





function submitForm() {
$.ajax({type:'POST',
url:'jquery-ajax-demo.php',
data:$('#ContactForm').serialize(),
success: function(response) {
$('#ContactForm').find('.form_result').html(response);
//#$(".form_result").html(response);
}
});

return false;
}







Your Name:
Your Email:
Your Message:





Your Name Is:
Your Email Is:
Your Message Is:









What is wrong? :(
Lucia Hustatyova
05/02/2012
Lucia Hustatyova
Sorry, i don't know how to paste the code :(
Lucia Hustatyova
05/02/2012
Lucia Hustatyova
Sorry, it's working, I just move PHP code immediately after body definition...
Anirudh
06/04/2012
Anirudh
I want to enter username & password from the user, match them with the username &passwords stored in my database, and if correctly matched, i want to open a new page..can you post the code for me?
Saurabh
06/14/2012
Saurabh
Thanks a lot for this scripting !!
Joe
06/15/2012
Joe
Hi - does anyone know how to integrate this type of AJAX/jQuery function into iContact's standard signup form? By default, the form submits to a success page or error page, but I'd rather the user stay on the page after submitting the form (without the page reloading) and have the success or error message show up (perhaps having the success message replace the form fields after the user submits the form successfully, but the form fields staying there and an error message generating if that's the result of their submission). Here's an example of the code of their signup form (I replaced my account info and my site's URL with fake info for example purposes):

HERE'S THE CODE FOR THE FORM ON MY SITE:









* First Name:







* E-mail:






* = Required Field















HERE'S THE CODE FOR A SCRIPT THAT THE FORM REFERENCES ON MY SITE:

var icpFormXXX = document.getElementById('icpsignupXXXX);

if (document.location.protocol === "https:")

icpForm2745.action = "https://app.icontact.com/icp/signup.php";
function verifyRequired2745() {
if (icpFormXXX["fields_fname"].value == "") {
icpFormXXX["fields_fname"].focus();
alert("The First Name field is required.");
return false;
}
if (icpFormXXX["fields_email"].value == "") {
icpFormXXX["fields_email"].focus();
alert("The E-mail field is required.");
return false;
}


return true;
}


Any suggestions as to how I can make this form work the way I want it to? Thanks for any help!!!
Joe
06/15/2012
Joe
Not sure why my message came up so weird
Joe
06/15/2012
Joe
OK - I can't figure out why the HTML isn't displaying in my comment box above...but I think you get the idea of what I'm talking about. Let me know if you need any additional info, thanks!!

HERE'S THE CODE:







* First Name:







* E-mail:














* = Required Field







Joe
06/15/2012
Joe
Yeah, the HTML for the signup form isn't displaying on here...I can e-mail it to you if needed.
ankur
06/21/2012
ankur
thanks to share this
ikenna
07/04/2012
ikenna
nice post...thanks a milliobn
sandip kc
07/13/2012
sandip kc
I'm curious if this code works if there are multiple forms on same page using same ajax function? where do i have to change my code to do that?
rdd
07/17/2012
rdd
how to submit image through form, using ajax?
Jason T. Stiles
07/17/2012
Jason T. Stiles
@sandip kc: you can use the same AJAX function, but you would need to pass in a parameter (the ID of the form) to the submitForm() function and then substitute "#ContactForm" with the value of that parameter.
Rex
07/24/2012
Rex
This is really cool, I just implemented on my site really cool, following yours I made one more http://www.webstutorial.com/ajax-contact-form-with-validation/ajax
Atrips
07/26/2012
Atrips
Thank you. :)
Excellent Article this tutorial about Jquery and Ajax is very good, Thank you finally I can finished my function.

Best regards,
Guillermo
ErinK
07/30/2012
ErinK
JQuery is Awesome. Thanks!
Ralph
08/08/2012
Ralph
Thanks a lot. It works so far. But how can I configure the php script to send the form to an email address?
Tushar
08/09/2012
Tushar
Thanks
Divya Rajput
09/07/2012
Divya Rajput
Hi,
I am making a career form and i want to sent this form on mail if somebody is filling the form . All function is working if i am not given function for uploaded file. If i give that , it is not working. Can you tell me how should i write code for uploaded file so that it will go on somebody's mail.

Thanks
Arian
09/12/2012
Arian
web developers have captcha in their sites
Sid
12/05/2012
Sid
Thanks buddy.. Nice demo.
DavidC
12/05/2012
DavidC
Just incase anybody is looking at using the code I pasted above please see below for a version which has been tidied up but still lacks the failed response


function submitForm(the_form,the_response_location,the_file) {
var the_form = document.getElementById(the_form);
var the_response_location = document.getElementById(the_response_location);

$.ajax({type:'POST', url:the_file, data:$(the_form).serialize(), success: function(responseText) {
the_response_location.style.display = "block";
the_response_location.innerHTML=responseText;
}});

return false;
}

On the form I used:

&lt;form id = "location_form_name" id = "location_form_name" method = "post" action = "javascript:nothing();"&gt;

On the button which is a type button I used:

&lt;button type = "button" onclick = "submitForm('location_form_name','location_error_area','update_filename.php');\" name = \"the_button\" id = "the_button"&gt;SUBMIT&lt;/button&gt;
Carsten/
01/10/2013
Carsten/
Hi Jason,

I have a question about this outstanding form using AJAX.

When submitted, how will I receive the inputs from the form in my email inbox?

Is there anyway this could be done easily and could you tell me.

Everything works out fine, so I really only need this to conclude it.

Best regards
//Carsten - Denmark
Jason T. Stiles
01/10/2013
Jason T. Stiles
@divya & @carsten - look into the PHP mail() function: http://php.net/manual/en/function.mail.php this should help you with what you want to do.
Naveen Kumar
01/11/2013
Naveen Kumar
Good Example
Carsten
01/11/2013
Carsten
Hi Jason,

We are trying to do something like this, but can´t get it to work properly:
"Form handler page"


Your Message Is:
Your Email Is:
Your Name Is:
Your Phonenumber Is:


Any advice on this ?

//Carsten - Denmark
Carsten
01/11/2013
Carsten
Did not come out right...

if(isset($_POST['name'])) {
$msg = $_POST['msg'];
$email = $_POST['email'];
$name = $_POST['name'];
$phone = $_POST['phone'];


Your Message Is: php echo $msg
Your Email Is: php echo $email
Your Name Is: echo $name
Your Phonenumber Is: echo $phone

}



$msg = $msg;


$msg = wordwrap($msg, 70);


mail('me@domain.dk', 'My Subject', $msg);

//Carsten - Denmark
Zarqdno za laptop
02/03/2013
Zarqdno za laptop
Thanks for sharing,
i'm just not sure for the purpose of the DIE statement there.

Best Regards
Dimi
soe yan naing
02/07/2013
soe yan naing
Hi,
I have a problem in my JQuery ajax passing parameters.

I would like to know " How to pass multi-parameter from JQuery ajax " into Server Method.

Thanks..
marcelo
02/08/2013
marcelo
Man,
thanks for your post very good
one question
how to make data appear in sequence one below the other?
Crazy
02/14/2013
Crazy
nice tutorial, i prefer submitting the data using post method and getting the php result using jquery, much easier.
Jared
02/26/2013
Jared
Cheers man, nice tutorial.
haider
03/17/2013
haider
How we can submit the form that contain array in it i.e; name="data[ABC][]"
Justin
04/13/2013
Justin
Hey,
Thanks very much for this tutorial. It's really good.

Justin
Abel William
05/30/2013
Abel William
I am very grateful, this tutorial really helped me!
peter sinot
06/02/2013
peter sinot
hello

is it possible that after 'submit' the form is clear again? now the inputkeep staying in the form.

thanks peter
Meenakshi
06/09/2013
Meenakshi
Hey Jason,

Thanks for this tutorial. It's very simple and precise.
name
07/01/2013
name
Nice tutorial
thanks
ARZ Kreatif
07/07/2013
ARZ Kreatif
tq dude
Plumber dublin 18
12/09/2013
Plumber dublin 18
Thank you for the work you have put into your nice blog. We will bookmark to your blog because it is very informational. We love the site and will come back to see your new posts.
I am genuinely keen of reading posts about building new blog, or perhaps concerning Web optimization.
gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
Deeapkd
03/07/2014
Deeapkd
d
dasd
03/14/2014
dasd
dsa
dasd
03/14/2014
dasd
dsaasdasda
erkan
03/14/2014
erkan
thank you for document!
admin
03/25/2014
admin
admin
03/25/2014
admin
sssss
03/26/2014
sssss
bn
03/28/2014
bn
bn
bn
03/28/2014
bn
bn
bn
03/28/2014
bn
bn
good work
good work
good work
zaqi
04/29/2014
zaqi
how to send data form to another page? or open the result form in another page?
This website
05/31/2014
This website
The pursuit of truth and beauty is a sphere of activity in which we are permitted to remain children all our lives.
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jhjh
06/06/2014
jhjh
hjhj
jyoti
06/06/2014
jyoti
nyc
fadz
06/09/2014
fadz

$(document).ready(function() {
$("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {

if
(
$("#NAME").val() == '' ||
$("#EMAIL").val() == '' ||
$("#MOBILE").val() == '' ||
$("#NOTE").val() == '' )
{ alert ("All field are required")
;}
else {
$.ajax({
type: "POST",
url:"www.url.com",
data: {
NAME: $("#NAME").val(),
EMAIL: $("#EMAIL").val(),
MOBILE: $("#MOBILE").val(),
NOTE: $("#NOTE").val(),
SOURCE: 'BAY SQUARE'
},
success: function() {
alert("We will contact you soon !");
},
dataType: 'html'
});

$("#NAME").val('');
$("#EMAIL").val('');
$("#MOBILE").val('');
$("#NOTE").val('');
}};





















Submit



my form is not working im trying it this way
fadz
06/09/2014
fadz

$(document).ready(function() {
$("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {

if
(
$("#NAME").val() == '' ||
$("#EMAIL").val() == '' ||
$("#MOBILE").val() == '' ||
$("#NOTE").val() == '' )
{ alert ("All field are required")
;}
else {
$.ajax({
type: "POST",
url:"www.url.com",
data: {
NAME: $("#NAME").val(),
EMAIL: $("#EMAIL").val(),
MOBILE: $("#MOBILE").val(),
NOTE: $("#NOTE").val(),
SOURCE: 'BAY SQUARE'
},
success: function() {
alert("We will contact you soon !");
},
dataType: 'html'
});

$("#NAME").val('');
$("#EMAIL").val('');
$("#MOBILE").val('');
$("#NOTE").val('');
}};





















Submit



my form is not working im trying it this way
This website
06/16/2014
This website
Pretty cool post. Itâs really very nice and useful post. Thanks for sharing this with us!itâs my first visit.
Pandu Aji Wirawan
06/17/2014
Pandu Aji Wirawan
I can't reset the textarea with jquery
Alossi A
06/19/2014
Alossi A
Thanks for this useful post! I've bookmarked for future reference. Another site that I also recommend that you haven't included in your post is http://www.dreame.biz. I love it because it has more than 50+ Tutorials.
Have something to say?
anonymous
07/12/2014
anonymous
this works perfectly. Thank you so much
All the contents you mentioned in post are too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.
xxxxx
07/25/2014
xxxxx

Have something to say?