Create a Ajax based Form Submission with jQuery

Written by Kevin Liew on 01 Apr 2009
394,201 Views • Tutorials


AJAX has changed the world of web development. Look at digg, facebook and gmail, thery are good examples to show the capability of AJAX. AJAX can create a highly responsive web interface and increase the user experience.

AJAX is abbrieviated from Asynchrounous javascript and XML. It's not a new technology, but the implementation of a group of technologies to achieve a seamless interaction between client and server.

Typically, xhtml and css to present the information, javascript is used to handle user interactions, and a server side language to perform the users' requests (and normally return data in XML format, in this tutorial, we won't do that), and it all is happening in the background using the Javascript XMLHttpRequest. Javascript plays a main role tie all these technologies together and create the asynchronous interaction between client ans server.

  • Reduce connections and bandwidth to the server, images, scripts, stylesheets only need to be downloaded once
  • Reduce loading timew. User doesnt have to load pages again and again, it all happens in a same page!
  • Increase responsiveness and end user experiences.
Usability Guidelines:
  • Always provide feedback to user. Let user know the server is processing the request. Indicate that using message or loading icon.
  • Prepare a plan to those users without Javascript support.


So, you know about the goodness of AJAX. Let's learn a simple way to implement it.

In this tutorial, we will learn form submission using jQuery without navigate out from the page. It accepts user input, processes it and sends it to a php file called "process.php". The PHP script will send a notification email to the recipient. Of course, in case browser couldn't support javascript/XMLHttpRequest, we have a second plan ready, the form will submit the data using the normal form submission.

How do we do that? Easy, we specified POST and ACTION attributes in the FORM element, if browsers couldn't support it, that will submit the form straight away. If the browsers could support it, the javascript will cancel the submit button default behaviour. And we need to code the PHP script to support both GET and POST methods and produce the result accordingly.


In this sample, I'll keep everything as simple as possible. This is how it looks like

<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message. 
	<div class="form">
	<form method="post" action="process.php">
	<div class="element">
		<input type="text" name="name" class="text" />
	<div class="element">
		<input type="text" name="email" class="text" />
	<div class="element">
		<input type="text" name="website" class="text" />
	<div class="element">
		<textarea name="comment" class="text textarea" /></textarea>
	<div class="element">
		<input type="submit" id="submit"/>
		<div class="loading"></div>
<div class="clear"></div>

2. CSS

I'm using CSS to make the 2 columns layout - LABEL and Form Elements. Also, some important classes:

  • .hightlight: Error indicator. if user had not entered anything in the textfield, it will highlight it and display an error icon
  • .loading: Loading animation icon. After user clicked on submit, if no errors were found, this icon will be displayed next to the submit button
  • .done: Success message. If the form is submitted successfully, display show this class

.clear {clear:both}

.block {
	margin:0 auto;
.element * {
.element label {
.element input.text {
.element .textarea {
.element .hightlight {
	border:2px solid #9F1319;
	background:url(iconCaution.gif) no-repeat 2px
.element #submit {
.loading {
	background:url(ajax-loader.gif) no-repeat 1px; 
.done {
	background:url(iconIdea.gif) no-repeat 2px; 
	margin:20px auto; 

3. Javascript

Finally, the Javascript code. I have added comments in each line to explain what it does.

First, we need a simple validation to ensure user has key in something. We can add more validations, like, email validation, valid character validation, length validation and so on. And it's a good practise to encode the data into URL friendly format as well.

What the code does:

  • Get user's input
  • Validate the data, if error found, add the hightlight class, and stop the script
  • If no errors were found, all text field will be disabled and format the data to be passed to jQuery ajax method
  • jQuery will appened the data to process.php, so it will look something like this:


    in fact, you can execute the process.php with that url.
  • process.php will return either 1 or 0, if 1 it meant mail was sent successfully, otherwise, mail was not sent.
  • If suceed, the form will be hidden and a message is displayed.
$(document).ready(function() {
	//if submit button is clicked
	$('#submit').click(function () {		
		//Get the data from all the fields
		var name = $('input[name=name]');
		var email = $('input[name=email]');
		var website = $('input[name=website]');
		var comment = $('textarea[name=comment]');

		//Simple validation to make sure user entered something
		//If error found, add hightlight class to the text field
		if (name.val()=='') {
			return false;
		} else name.removeClass('hightlight');
		if (email.val()=='') {
			return false;
		} else email.removeClass('hightlight');
		if (comment.val()=='') {
			return false;
		} else comment.removeClass('hightlight');
		//organize the data properly
		var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
		+ website.val() + '&comment='  + encodeURIComponent(comment.val());
		//disabled all the text fields
		//show the loading sign
		//start the ajax
			//this is the php file that processes the data and send mail
			url: "process.php",	
			//GET method is used
			type: "GET",

			//pass the data			
			data: data,		
			//Do not cache the page
			cache: false,
			success: function (html) {				
				//if process.php returned 1/true (send mail success)
				if (html==1) {					
					//hide the form
					//show the success message
				//if process.php returned 0/false (send mail failed)
				} else alert('Sorry, unexpected error. Please try again later.');				
		//cancel the submit button default behaviours
		return false;

4. PHP

This PHP code can accomodate different type of submissions (POST and GET). If the user submitted the form using jQuery, process.php will get the data from GET. and if the browser couldn't run javascript, the data will be sent using POST. What it does:

  • Retrieve user's input from either GET or POST method
  • If POST, set the $post variable to 1. This is to display the message instead of return the result
  • Then, perform the server side validation if the form was submitted using POST
  • If no errors were found, organize the data into a html email template and send it to the email we have specified.
  • Display the message if POST is used. Display result (either 1 or 0) if GET is used

//Retrieve form data. 
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];

//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;

//Simple server side validation for POST data, of course, 
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.'; 
if (!$comment) $errors[count($errors)] = 'Please enter your comment.'; 

//if the errors array is empty, send the mail
if (!$errors) {

	//recipient - change this to your name and email
	$to = 'Your Name <>';	
	$from = $name . ' <' . $email . '>';
	//subject and the html message
	$subject = 'Comment from ' . $name;	
	$message = '
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	<html xmlns="">
		<tr><td>Name</td><td>' . $name . '</td></tr>
		<tr><td>Email</td><td>' . $email . '</td></tr>
		<tr><td>Website</td><td>' . $website . '</td></tr>
		<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>

	//send the mail
	$result = sendmail($to, $subject, $message, $from);
	//if POST was used, display the message straight away
	if ($_POST) {
		if ($result) echo 'Thank you! We have received your message.';
		else echo 'Sorry, unexpected error. Please try again later';
	//else if GET was used, return the boolean value so that 
	//ajax script can react accordingly
	//1 means success, 0 means failed
	} else {
		echo $result;	

//if the errors array has values
} else {
	//display the errors message
	for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
	echo '<a href="form.php">Back</a>';

//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	$headers .= 'From: ' . $from . "\r\n";
	$result = mail($to,$subject,$message,$headers);
	if ($result) return 1;
	else return 0;


Now you know how to build a ajax based form submission that will work even if the browser doesnt support javascript using jQuery. Make sure you check out the demo and download the source code to play with it. Last but not least, I need your support :) If you like this article, please help me to promote it by adding this post into your bookmark. Or you can subscribe to my RSS for more posts. Thanks!

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

Nick 11 years ago
Thanks for posting this. It is a big help.

I think I have most of everything working. Validation works fine, when I click submit, the loader .gif shows, but then the page loads process.php and just displays a 1. Any help would be greatly appreciated.
Kevin Liew Admin 11 years ago
That's interesting, it means it didn't execute the ajax but load the process.php straight away. You need to use firebug Net feature to see the request.
weliftoff 11 years ago
Hi Kevin,

Thanks for the great script. Just got one question, how do you able to input details again after you submit the form? Because when you refreshed the site, it won't allow you type again but you can resubmit the details.

Any idea?


weliftoff 11 years ago
Hi Kevin,

It's me again. I think the problem is with firefox since it's work with safari but haven't check the form in IE. I just remove this code in the script

//disabled all the text fields

and it's work like a charm. I can input details again after I refresh the page. I don't know if there something going wrong with the script after removing that lines of code.

Again nice scripts. Thanks!
Kevin Liew Admin 11 years ago
It's fine. Maybe you want to clear all the fields as well. :)
Okan 11 years ago
Thanks for this great tutorial, I implemented my site's add comment part with ajax as you instructed. However, on $.ajax even though it succesfully calls php file and do everything as I need but never return with html. So cannot fadeOut loading div or get any alert about exception. What could be the reason? Thanks in advance.
M 11 years ago

Thanks for the script. Working just amazing! The only problem - spam. Any solution for that?
Gina 11 years ago
It seems to be working fine, but I can't get emails from it. And what I downloaded is different than whats been posted on this page.
Kevin Liew Admin 11 years ago
Hi Gina, you need to make sure your server allow mail function. Also, in the download file, it has 2 process.php, one is a dummy version just to demonstrate the ajax call, the other with label "working version" will send out email. You need to rename it to process.php
Waqas 11 years ago
I am stuck with one thing. Is that possible to use same code with same method but addition with file upload option? Thanks
Kevin Liew Admin 11 years ago
I think you will facing a steep learning curve. It isn't easy to make a ajax file upload.

There are plenty of already made ajax file upload, you might want to check them out.
Gene 11 years ago
Nice looking code! I changed my email address on process.php and did some testing. I'm getting the success message, but I'm not getting the email. hmmm...
Kevin Liew Admin 11 years ago
from the PHP script, it only return success if the php mail() function return true. Check your spam mail?
David 11 years ago
Great script. Any idea why it sends 2 emails and 2 notification emails when the form is submitted? Thanks
David 11 years ago
never mind, I think it was the way I called the javascript. I'm using AJAX loaded pages and called the js as a remote file. When I wrap the code in a jquery ajaxcomplete method it works great.
Andres 10 years ago
Can you please show the code you wrote to achieve this? Because I am also receiving 2 emails at a time.
Stephen Cunningham 11 years ago
This is completely awesome script and works perfectly - thanks. Just a few questions. 1) how do i parse a drop-down selection? My email states "undefined" where the selection should go and, 2) can the form reappear after 3 seconds all cleared. Great work.
Kevin Liew Admin 11 years ago
Hi Stephen, when i was creating this tutorial, something i didn't think it through. You actually can do this to make your life easier:

give the <form> an ID, eg #form, then you can use $('#form').serialize() which will construct data and submit it to the PHP script
JP 11 years ago
hello I'm working with this code seems very good resource.

but I have a question on the same page I did put a contact form below and separately in another part of the input page to put a email to subscribe but does not work and copy the code i email some how I can get right comflicto this thanks and good work .
Pablo del Rio 11 years ago
Hey Kevin Liew, is great thanks! I do a query as to have two forms that work with your script?
Kevin Liew Admin 11 years ago
The least complicated way to do it is:

$('#form1 .submit').click(function () ....
$('#form2 .submit').click(function () ....

basically, you need to duplicate the script and modify to adapt to each of your form.
Peter 11 years ago
How do you add a second email, so that the people who submit get the same email to?
Kevin Liew Admin 11 years ago
In php, separate the email with a comma,
$to = 'Your Name <>, Your Name <>';