Create a Ajax based Form Submission with jQuery

Demonstration Download

AJAX

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.

Advantages:
  • 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.
Advertisement

Introduction

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.

1. HTML

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>
	<div class="form">
	<form method="post" action="process.php">
	<div class="element">
		<label>Name</label>
		<input type="text" name="name" class="text" />
	</div>
	<div class="element">
		<label>Email</label>
		<input type="text" name="email" class="text" />
	</div>
	<div class="element">
		<label>Website</label>
		<input type="text" name="website" class="text" />
	</div>
	<div class="element">
		<label>Comment</label>
		<textarea name="comment" class="text textarea" /></textarea>
	</div>
	<div class="element">
		
		<input type="submit" id="submit"/>
		<div class="loading"></div>
	</div>
	</form>
	</div>
</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
body{text-align:center;}

.clear {clear:both}

.block {
	width:400px;
	margin:0 auto;
	text-align:left;
}
.element * {
	padding:5px; 
	margin:2px; 
	font-family:arial;
	font-size:12px;
}
.element label {
	float:left; 
	width:75px;
	font-weight:700
}
.element input.text {
	float:left; 
	width:270px;
	padding-left:20px;
}
.element .textarea {
	height:120px; 
	width:270px;
	padding-left:20px;
}
.element .hightlight {
	border:2px solid #9F1319;
	background:url(iconCaution.gif) no-repeat 2px
}
.element #submit {
	float:right;
	margin-right:10px;
}
.loading {
	float:right; 
	background:url(ajax-loader.gif) no-repeat 1px; 
	height:28px; 
	width:28px; 
	display:none;
}
.done {
	background:url(iconIdea.gif) no-repeat 2px; 
	padding-left:20px;
	font-family:arial;
	font-size:12px; 
	width:70%; 
	margin:20px auto; 
	display:none
}

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:

    http://[your-website-url]/process.php?name=kevin&email=[email protected]&website=http://www.queness.com&comment=Testing%20of%20Ajax%20Form%20Submission

    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()=='') {
			name.addClass('hightlight');
			return false;
		} else name.removeClass('hightlight');
		
		if (email.val()=='') {
			email.addClass('hightlight');
			return false;
		} else email.removeClass('hightlight');
		
		if (comment.val()=='') {
			comment.addClass('hightlight');
			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
		$('.text').attr('disabled','true');
		
		//show the loading sign
		$('.loading').show();
		
		//start the ajax
		$.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
			success: function (html) {				
				//if process.php returned 1/true (send mail success)
				if (html==1) {					
					//hide the form
					$('.form').fadeOut('slow');					
					
					//show the success message
					$('.done').fadeIn('slow');
					
				//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
<?php

//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 <[email protected]>';	
	//sender
	$from = $name . ' <' . $email . '>';
	
	//subject and the html message
	$subject = 'Comment from ' . $name;	
	$message = '
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head></head>
	<body>
	<table>
		<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>
	</table>
	</body>
	</html>';

	//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>';
	exit;
}


//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;
}
?>

Conclusion

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!

Demonstration Download

AdvertisementOur N10-004 prep course & cisco ccna include the latest set of 646-205 dumps practice questions and 70-642 dumps with 100% guarantee for victory in 642-457.

Show Some Love, Spread This Post!

249 comments

Stephen Cunningham Fri, 20th January 2012 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.
Reply
David Tue, 17th January 2012 Great script. Any idea why it sends 2 emails and 2 notification emails when the form is submitted? Thanks
Reply
David Tue, 17th January 2012 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.
Gene Wed, 11th January 2012 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...
Reply
Kevin Liew Thu, 12th January 2012 from the PHP script, it only return success if the php mail() function return true. Check your spam mail?
Waqas Wed, 14th December 2011 I am stuck with one thing. Is that possible to use same code with same method but addition with file upload option? Thanks
Reply
Kevin Liew Tue, 20th December 2011 I think you will facing a steep learning curve. It isn't easy to make a ajax file upload.
http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery

There are plenty of already made ajax file upload, you might want to check them out.
Gina Thu, 1st December 2011 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.
Reply
Kevin Liew Mon, 5th December 2011 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
M Wed, 2nd November 2011 Hey,

Thanks for the script. Working just amazing! The only problem - spam. Any solution for that?
Reply
Okan Fri, 28th October 2011 Hi,
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.
Reply
weliftoff Sun, 16th October 2011 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
$('.text').attr('disabled','true');

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!
Reply
Kevin Liew Sun, 16th October 2011 It's fine. Maybe you want to clear all the fields as well. :)
weliftoff Sun, 16th October 2011 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?

Thanks!

Reply
Nick Tue, 11th October 2011 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.
Reply
Kevin Liew Thu, 13th October 2011 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.
itllk Tue, 11th October 2011 Doesn't work for me... i've literally copied and pasted the code to then modify and it's returning: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/inc_marketing/victoriasquare.com/facebook/vsqapp/ajax/process.php on line 28
Reply
Kevin Liew Thu, 13th October 2011 Please download the demo instead of copy & paste.
Jaum Sat, 8th October 2011 How I redirect to a Thank you Page?
Reply
Kevin Liew Mon, 10th October 2011 Jo Jaum, in the javascript, $.Ajax call, on success, you can add a line like below:

if (html==1) {
//hide the form
$('.form').fadeOut('slow');

//show the success message
$('.done').fadeIn('slow');

window.location = 'http://www.url.com/thanks-you-page.html';
............
............
prateek Mon, 3rd October 2011 Good example
Reply
~z~ Mon, 19th September 2011 Great tutorial, thank you. What would be the correct way to implement checkboxes? I've been able to successfully send the values by using

var check = $(document.testb.mycb[0].value);

&

foreach($_POST['check'] as $value) {

$check_msg .= ": $value
";

}

but this creates a few problems- upon submit, process.php opens in new page, also if no checkboxes are chosen, a php error is visible with $result.


Many thanks in advance.
Reply
Zach Tue, 6th September 2011 Thanks for this tutorial - has some great info. Only thing I was curious about: Isn't the GET method a non-conventional way of doing this? I had an issue with duplicate entries using this code, and used POST instead and has since been fixed. Just curious - guys on StackOverflow said it's not a normal convention to use GET for something like this, but rather to get variables in the url etc
Reply
Kevin Liew Tue, 6th September 2011 Hi Zach, you're right. When I was writing this tutorial I was pretty new to jQuery. Yes, the best way to do it is using POST in ajax().
Chris Wed, 31st August 2011 Please excuse what may be a simple beginner error but i am a complerte noob at PHP and jquery

I seem to be having an issue with the success message.

Using the tutorial files (with just changing the email address in the process.php) when i hit send, the process.php form is getting all the required data from the form, and sends the mail correctly, ( it arrives in my inbox.) but does not seem to be returning the right result back to the jquery script, as the message "Sorry, unexpected error. Please try again later." appears no matter what i try.

I have checked the PHP error logs on my server and have the following entries for every submission time

"31-Aug-2011 14:50:50] PHP Notice: Undefined variable: errors in C:inetpubwwwrootinprocess.php on line 20"

this is the only hiccup in what has to be the best online tutorial for this type of form, and chance of a pointer in the right direction ?
Reply
Kevin Liew Wed, 31st August 2011 Ok, good to have error. PHP works fine. It must the $error variable.
Put this in line 1:
$error="";

my tips to debug ajax webpage is using firefox + firebug. You can inspect the error by using the net tab in firebug to see what the form sent and what have returned.
Chris Wed, 31st August 2011 Worked like a charm,

Thank you
keith Wed, 24th August 2011 I know this might seem like a stupid question, but where do you put your email in so that you recieve peoples emails
Reply
Kevin Liew Wed, 24th August 2011 PHP Section, Line 24.
JMarc Tue, 26th July 2011 Thank you very much for sharing the script. The script works well if I used it on its own. However, when I integrate it to my page, it does not do what it is supposed to do. Here is what I am trying to do: on my main_page, I have several links. Each link opens a form into a div on main_page.
Once a form is loaded into the div, I want to be able to submit the form and have only that div to be refreshed.


The links on my main_page.php are called by: <a javascript:ajaxpage('form1.php','div_target')>form1</a>
"ajaxpage" is a function that enable to load form1.php into the div_target on main_page.php
For test purposes, I renamed form1.php in the link above: jquery-ajaxform.php and used your files.
When I click on the submit button, the file process.php loads.
I am sure i ma missing something, but I don't know what?


Reply
Sundar Visweswaran Fri, 26th August 2011 I am also facing the same problem. How did you fix it?
Kevin Liew Sun, 28th August 2011 It's hard to see the issue. Is there any chances you can setup a test site?
Josh Sat, 16th July 2011 Hey Kevin,

The form always seems to POST normally and ignore the AJAX. Any ideas?
Reply
Kevin Liew Sun, 17th July 2011 make sure jquery is linked properly.
BD_Design Thu, 14th July 2011 Great tutorial, thank you.

One question though, in your process.php script you set the $post flag (line #12) if the form is submitted using the post method (non-js), but then you never use the $post flag again - why set it? Perhaps you meant to use it in the if/then statement on line 49, instead of 'if ($_POST)' ?

Thanks again!
Reply
Kevin Liew Wed, 24th August 2011 Oops! Yes, you're absolutely correct. I guess it meant to be used in line 49. I must have forgotten about it!

Leave a comment

Have something to say? Drop a comment! No HTML tags are allowed in the comment textfield.

Advertisement