Register now or login here to start promoting your blog and your favourite articles.
Create a Ajax based Form Submission with jQuery
1 Apr 2009 - 82 Comments
Wondering how to submit a form in a same page, and display the submission result with some fancy fadeOut or slideUp effect? In this tutorial, I will show you how to make Ajax Based form submission with jQuery and it will also work even if javascript is not supported.
Author: kevin | Source: queness
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.

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=kevin@test.com&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 <your@email.com>';	
	//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

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

JDStraughan on 3 Apr 2009 says:
Great tutorial. Added to http://tutlist.com
Willem Vyent on 9 Apr 2009 says:
Hi,

Why the isn't cloced in your example download (file: jquery-ajaxform.php, line 135 and 136)?

line 135:
line 136:


Kind Regards,

Willem Vyent
The netherlands
kevin on 9 Apr 2009 says:
@Willem: haha, yea, I have forgotten to close the <head> tag! thanks.
florian on 13 Apr 2009 says:
I love this tutorial and was able to implement on a static contact page for one of my websites.

However, I tried to implement for a more complex webstie that runs on expression engine and I was getting an error message after hitting submit, before the form was sent. Is there anything that I need to pay attention to?
djmarcel on 15 Apr 2009 says:
broodje piemel, erg lekker!
snapper on 16 Apr 2009 says:
Kevin...
I have a script that I am building with a different validation method and loading method. Is it possible for you to take a look see and guide me to the best route for processing it?
sergi on 21 Apr 2009 says:
the "copy to clipboard" feature for the html code isn't working. i dig the tutorial though.
sergi on 21 Apr 2009 says:
"be my partner" doesn't seem to be working either. [firefox, 3.0, windows xp]
kevin on 21 Apr 2009 says:
@sergi: thanks for digging! I have fixed that broken link :)... not so sure about the copy to my clipboard thingy...
anonymous on 30 Apr 2009 says:
nice job stealing someone else work:
http://nettuts.com/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
kevin on 30 Apr 2009 says:
I think you have not read my article before you start commenting. It might look similar superficially, but internally, the html, css, and javascript are written without referring to nettuts'. And try to disable your javascript and run nettuts', you will see the difference.

I respect genuine and orginal posts and I hate stealing hardwork from others. If I do, I will definitely give a huge credit to the author.

Mike VanTassell on 12 May 2009 says:
I have just implemented this tutorial. Works great in IE7, I cannot seem to get the form div to fade out in firefox. any suggestions? here is a link to my page

http://www.brooklynitehockey.com/contact.shtml
♦Albert Pak on 14 May 2009 says:
Sweet! Love this!
Jordan on 24 May 2009 says:
To the person that was claiming you stole this from the NetTuts website, he's 100% wrong. This implementation is way better, not to mention this was a better written tutorial. Great work.
Nico on 2 Jun 2009 says:
Hi! Great tut and works great...was so much easier than the Nettut one!

just one thing...When the form validates is there supposed to be text that appears? Cant seem to work it out.
rik on 5 Jun 2009 says:
if i wanted to display a image or animated gif instead of it saying thank you blah blah blah would i put that in the process .php?
and how would i do that , just reference a file in my images folder? and why does it have a form.php as a back anchor tag? confused me alittle (not that , that is hard). thank you its great . ive got it all to work just wanted a few mods....
kevin on 5 Jun 2009 says:
@rik: hi rik, if you want to change the thank you message, for the html code, in line 3 and in the php file in line 50.

Thank you message will be displayed if user's browser doesn't support javascript. You can try that by disabling your javascript and submit the form. Just becareful when editting php file.

And yes, if you want to put image, just reference the file in the images folder.

eg, line 50 you might want to change it to:
echo '';

and lastly, the Back Link in the php file, you will see it after you disabled javascript and submit the form. : )
kevin on 5 Jun 2009 says:
@Nico: the form validation in php file (those error message) will only be displayed if browser doesn't support javascript.

If it supports javascript, javascript will stop the normal form submission and using ajax instead. However, if javascript is not supported, the form will submit using normal form submission, and send the post data to the php file.
Stef on 9 Jun 2009 says:
Great script. Got it working, only I can't seem to figure out where to put my "action" - i.e. to send the message or to manipulate my database.
I tried to do it right after
if ($_POST) {
echo 'Thank you! We have received your message.';
in process.php my did not work.
kevin on 9 Jun 2009 says:
@Stef: Hi there, you can only see the message if you have your javascript disabled or if POST method was used. Otherwise, you won't able to see it because javascript has taken over the submission process. Try to disabled your javascript, and you will get it. : )
Roe Lee on 12 Jun 2009 says:
Thanks ! it's very helpful for me
biometryka on 14 Jun 2009 says:
Nice write up.
owner of biometria
Rob on 29 Jun 2009 says:
Will this work with coldfusion?
kevin on 29 Jun 2009 says:
@Rob: yes, it will work, but you will have to write the server side script in coldfusion, the output should be either 1 or 0 to indicate suceed or failed.
TutsKing on 6 Jul 2009 says:
This Great Tutorial has been added to the list of High Quality Tuts at TutsKing.com
Colin on 13 Jul 2009 says:
Thank you for taking the time to explain this process. This was really helpful in learning the process to creating what usually goes into 90% of websites.
Jared on 28 Jul 2009 says:
This is a very helpful tutorial! Thank you for articulating the process so thoroughly.

Does anyone here have suggestions on how the code could be tweaked to enable form validation on all the fields simultaneously? (i.e.: right now, if a user leaves every field empty and clicks "submit," only the "Name" field returns an error. if the user proceeds to fill in the "Name" field [but doesn't fill out the other fields] the next field "Email" returns a validation error. This works, but isn't the ideal implementation as the user is currently notified of validation errors one at a time.)
kevin on 28 Jul 2009 says:
Hi Jared: Yes, you can do that, in the javascript, in each of the validation, it return false. So, just replace it with:

if (name.val()=='') {
name.addClass('hightlight');
error=1;
} else name.removeClass('hightlight');

if (email.val()=='') {
email.addClass('hightlight');
error=1;
} else email.removeClass('hightlight');

if (comment.val()=='') {
comment.addClass('hightlight');
error=1;
} else comment.removeClass('hightlight');

if (error) return false;


so, instead of terminate the script if an error was found, you terminate it after all errors were found. :)
ADIL Younes on 10 Sep 2009 says:
nice tutorial...good job
Barton on 13 Sep 2009 says:
Hi, love the simplicity of the method.
One question, where do the input box errors in the process.php get displayed?
Line 61 -> 4, PHP

Thanks and great job,

Barton.
Dinesh on 23 Sep 2009 says:
i have the below code for select maximum 2 image from a given images.



function SelectQPItem(itemid,obj,bid,ind){
var available=-1;
for(var i=0;i=0){
a_trade_qpi[available][0]=ind;
a_trade_qpi[available][1]=itemid;
$(\#$baseiditem\+ind).css(\border\,\$border_click\);
}
}
read the next message
Dinesh on 23 Sep 2009 says:


i want to reset means unselect the selected image for that i have writen the following code. but it is not working while i am reset.

function UnselectQPItems(){

for(var i=0;i
Dinesh on 23 Sep 2009 says:
i want to reset means unselect the selected image for this i have writen the following code. but it is not working while i am reset.

function UnselectQPItems(){

for(var i=0;i
Dinesh on 23 Sep 2009 says:
function UnselectQPItems(){
for(var i=0;i
Dinesh on 23 Sep 2009 says:
function UnselectQPItems(){for(var i=0;i
Mark on 24 Sep 2009 says:
Hi nice tutorial,

But i've added the followin,


Employed




Select


YES


NO




but once the form is submitted the selected option doesn't show in the submitted e-mail??

Any ideas??
Mark on 24 Sep 2009 says:
Hi nice tutorial,

But i've added the followin options to the form,


label>Employed
Select
YES
NO
kevin on 24 Sep 2009 says:
Hi Mark, have you added the extra form field variable in the php script?

Mark on 25 Sep 2009 says:
yes i have, but still it doesnt mail it!

$member = ($_GET[member]) ?$_GET[member] : $_POST[member];
jaxoo on 3 Oct 2009 says:
nice script thanks for sharing...
don luttrull on 27 Oct 2009 says:
thank you for this information, ajax forms here I come!
Pozycjonowanie Olsztyn on 31 Oct 2009 says:
Great tutorial :)
Eric Watson on 1 Nov 2009 says:
Perfect tutorial Kevin! Thank you for taking the time to write it. I've hit a snag and if you have a moment I was hoping you could point me in the right direction?

I've got a local working copy of your tut, and I have a local working copy of bassistance.de jquery validation. I\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ve married the two, but unfortunately I can't get it working seamlisly. In short, it is defaulting to your validation and not my more strick, bassistance validation. Basically, it will send the form and give the thank you message with anything in the inputs (i.e. It doesn't have to be a valid email, URL, etc).

Do you think it's possible to combine the two so I can get the best of both? I can post code if need be. Thanks for your time!
Jimmy on 5 Nov 2009 says:
hi Kevin, great tutorial!

I have a problem though, hope you can help me.

How do I make the comment textarea dissappear? If I delete the textarea element, and all the comment variables, the form wont be hidden. But as long as the comment in the form is there, the form can be hidden after clicking submit.

thanks
Jimmy on 5 Nov 2009 says:
hi Kevin, I just found out that my previous problem is not happening in Internet Explorer. But it happens on Firefox and Chrome.

Any suggestions how to make the form fade on Firefox (after removing the comment textarea)?

Thanks
kevin on 5 Nov 2009 says:
@eric, Im sure you can put javascript validation, you just have to add extra validation in this code: (eg email)

if (email.val()==) {
email.addClass(hightlight);
return false;
else if (validate email format) {
email.addClass(hightlight);
return false;
} else email.removeClass(hightlight);

something like that :)

@jimmy, I have tested with firefox, the form fadeOut after submission. its working.
Dave on 16 Nov 2009 says:
Hello,

Thanks for sharing your work.
Is it possible to how i can add a reply/copy/confirmation message to the sender?
I\\m trying to expand the form to some kind of \\order\\ form to book an artist. And it would be great if the person who \\ordered\\ gets a confirmation with extra details in that email.
And adding other form elements like radio buttons, select menus etc It\\s just a default way of html work?

Thanks and looking forward for an answer.

Dave
fullsalarm on 29 Nov 2009 says:
Very nice Job!Thanks
something related http://www.phpstring.co.cc/ajax-registration-module/
John on 18 Dec 2009 says:
Hey Kevin, thx for this script, its awesome. I managed it to style it and get it working but the ajax part never worked for me. When I hit submit, it loads the process.php and prints either the error or the sucess message.

So it does work but with no ajax, which is what I wanted more. Any ideas on why that is? I tested yours alone (previous to integrate it to my page) on my server and the ajax worked, so I know its not a server issue.

If you want to take a look its www.invitrostudio.com (one page site) thanks!
John on 18 Dec 2009 says:
My bad, the url is

http://invitro.vegasoftweb.com/1.0/
John on 18 Dec 2009 says:
Nevermind, I fixed it. Turns out the script was conflicting with others that use the same variable. The No-Conflict mode fixed it just fine.
Ade on 22 Dec 2009 says:
Wow!!!

This is one of the best tutorials I have ever used. The example code is commented brilliantly! I have been trying to get something like this working for ages and searched loads of tutorials and examples on google.

this is defenitly the best!

I have got everything working in my own style, few little misshaps on the way, watch out for .hightlight / .highlight

I am not that great with javascript and php, so now just have to work out how to add some more in depth validation within this code.

hmm?
Article submission on 4 Jan 2010 says:
great job

thanks for sharing
Francesco on 5 Jan 2010 says:
What about validation? it seems to simply...how to make some controls like trim or regex validation for email?
kevin on 6 Jan 2010 says:
@Francesco: yes, you need to add the validation code in javascript:

if (email.val()=='') {
email.addClass('hightlight');
return false;
} else if (email validation) {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');


and also in PHP:
if (!$email) $errors[count($errors)] = 'Please enter your email.';
else if (email validation) $errors[count($errors)] = 'Please enter a valid email.';
sossimo on 6 Jan 2010 says:
Hello, I am currently trying out the Ajax based form and I'm kinda experiencing some problems with it. I actually make it worked, but the things is after I have just tested it, and send my query, the thank you message will appear and then the whole form is gone now. Even after I switch tabs and go back to Contacts page, I still cannot see the Form. Please reply. Thanks! Also, I think this form really rocks! Good job!

- John
WeaponsTheyFear on 10 Jan 2010 says:
I am new to JQuery and Javascript in general. I uploaded the files to localhost and everytime I try it I get the error message.

I can't sendmail with php off localhost since its not setup to yet, but I set the result to true to test it and removed the attempt to send mail but still getting errors.
kevin on 11 Jan 2010 says:
Hi WeaponsTheyFear... haha.. interesting name!

what kind of error? php error? can you show me?
Sebastian on 12 Jan 2010 says:
thank you for this tutorial!

can it be that radio-buttons will not work?
i think if you use an input type=radio it will always take the value of the first radio button.
is there a soloution to use radio-battons as well?
mithila on 21 Jan 2010 says:
This is very good.
Add Post a comment method (leave a comment) it's very use full.
Ade on 23 Jan 2010 says:
Hi, I commented on this tutorial a while ago, saying how great it was.

I'm just struggling a bit now, trying to add some email validation. I'm not great at php, do i need to create a php email validation function and then call it somehow within this php code. I don't reall know what I'm talking about.

It's just it says in the tutorial (of course you should also add some email validation), I just don't know how to incorporate such validation into this code.

any help would be great :o)
kevin on 23 Jan 2010 says:
Hi Ade, I read ur comment before, I thought you would able to figure it out. Alright, here is it. At the moment, the php script to make sure user has entered something in the email field.

php script:

replace:
if (!$email) $errors[count($errors)] = 'Please enter your email.';

with:
if (!$email) $errors[count($errors)] = 'Please enter your email.';
else if (!filter_var($form['email'], FILTER_VALIDATE_EMAIL)) $errors[count($errors)] = "Invalid Email";

php itself has built in data sanitizer. I hope your php support it, if it doesn't please drop another comment :)
Ade on 24 Jan 2010 says:
Hi Kevin,

Thanks for the speedy support! I tried what you suggested, but it just caused an error with every email address I entered, not sure if this means my php doesn't support the data sanitizer?

I've been looking at some email validation code at the following page and was wondering if it would be possible to incorporate a similar email validation function into your code?

http://www.linuxjournal.com/article/9585

Any advice would once again be very much appreciated!

thanks
kevin on 24 Jan 2010 says:
Hi Ade, yes, I think your version of php doesnt support it... and yes again, you can use that email validation script... I was using that script before! haha...

based on that function :
check_email_address() it return true if the email is valid, otherwise return false...

so, do this:

if (!$email) $errors[count($errors)] = 'Please enter your email.';
else if (!check_email_address($form['email'])) $errors[count($errors)] = "Invalid Email";

not sure if you understand this:
!check_email_address($form['email'])

see the exclamation mark right in front? it means, NOT, so, if the return result/email is NOT true (false)...

haha, hope you can understand. :)
Ade on 26 Jan 2010 says:
Hi,

Thanks again for your help, I really really appreciate it!

Unfortunately I am still struggling, probably just being stupid, but can't seem to get an email validation sorted. I'd really like to just get it working! :o)

I think you may have been looking at a validation function higher up the page on the link I posted. Lower down the page under the heading "Listing 9. A Complete E-mail Validation Function" is a function named "validEmail"

If possible I'd like to try and incorporate this function. Would I just place the function code above your code and then do a similar thing to what you suggested with the if / else if statement?

Just really struggling to get the equivalent of the following line of code working with the "validEmail" function.

else if (!check_email_address($form['email'])) $errors[count($errors)] = "Invalid Email";

Probably something simple, but just can't get it working :o(

any ideas? sorry about this! :o)
kevin on 26 Jan 2010 says:
Hi, you just have to change the function name from check_email_address to validEmail:

if (!$email) $errors[count($errors)] = 'Please enter your email.';
else if (!validEmail($form['email'])) $errors[count($errors)] = "Invalid Email";

haha, u really struggle with php :p let me know if you need somemore help :)
Ade on 26 Jan 2010 says:
Hi Kevin,

I know, I'm pretty rubish! :o)

I had tried that, but just keep getting Invalid email for every email address I enter.

What is the $form in the following line of code:

else if (!validEmail($form['email'])) $errors[count($errors)] = "Invalid Email";

I think I understand that the function checks for a valid email address, if the email is not valid it sets the variable '$isValid = false' however if the email is valid it just does 'return $valid'

so I guess I just need to show an 'invalid email message' if the function named 'validEmail' does not return $isValid

Am I kinda there? does this code do that?

else if (!validEmail($form['email'])) $errors[count($errors)] = "Invalid Email";

or is there another way line of code I could try?

Sorry again for being so rubish! I'm really trying here :o)
Ade on 26 Jan 2010 says:
Hey, I think I may have finally got things working. I put the vadidEmail function in a seperate php file and then required that file once at the top of your code.

I then added the following lines of code to check if the function was true or false:

if (!$email) $errors[count($errors)] = 'Please enter your email.';
else if (!validEmail($email)) $errors[count($errors)] = "Invalid Email";

I think it might be working, does it look OK or am I just kidding myself that it is working correctly? :o)
kevin on 26 Jan 2010 says:
hi Ade, congrat... yea.. that looks good to me :) have you tried it by entering invalid email?
ugg boots on 26 Jan 2010 says:
Ok, I see what you're saying. I think I'm gonna have to look into this more...
ugg boots on 27 Jan 2010 says:
Ok, I see what you're saying. I think I'm gonna have to look into this more...
Ade on 27 Jan 2010 says:
Hi Kevin,

Yeh, it seems to work ok. I'm still unsure of what's the best email validation function out there to use really. There's so many!

I changed from my original validEmail function to one if found by Dominic Sayers at the following address:

http://code.google.com/p/isemail/source/browse/trunk/is_email.php

People seem to think it's a good one, so I think I may stick with it, what do you think of it, any better suggestions?

Thanks again for all your help in getting me to this stage!
kevin on 28 Jan 2010 says:
no worries ade. i think is_email is the way to go. I know validEmail has some validation bugs in it... some weird but valid email can be validated as invalid email.
ade on 28 Jan 2010 says:
Yeh, I thought is_valid looked pretty solid, I'm gonna stick with it.

Thanks again, I may be back :o)

ade
Ade on 28 Jan 2010 says:
Me again!

Soz, I meant is_email in my last post, not is_valid

:o)
kevin on 28 Jan 2010 says:
haha, i was thinking u must have found another new function :). Thanks for your support :)
Bill on 2 Feb 2010 says:
@kevin - When I replace the original code with yours, I lose the ajax functionality. Any ideas?

I'm also interested in validating the email address, but I'm not sure how to incorporate that function into this script.
Bill on 2 Feb 2010 says:
I just reread my post and I didn't specify which code I was talking about.


if (name.val()=='') {
name.addClass('hightlight');
error=1;
} else name.removeClass('hightlight');

if (email.val()=='') {
email.addClass('hightlight');
error=1;
} else email.removeClass('hightlight');

if (comment.val()=='') {
comment.addClass('hightlight');
error=1;
} else comment.removeClass('hightlight');

if (error) return false;
kevin on 2 Feb 2010 says:
Hi Bill, are you looking for email validation with javascript? you can do this:

if (email.val()=='') {
email.addClass('hightlight');
error=1;
else if (!validEmail(email.val())) {
error=1;
} else email.removeClass('hightlight');


and you need to add this function:

function validEmail(str) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


that's is a simple function to validate email, you might want to have a better one.

Let me know if you still need further assistance. Cheers :)
Bill on 3 Feb 2010 says:
I had my friend look at the script and he came up with this code:

if ((email.val()=='') || (email.val().indexOf("@")==-1) || (email.val().indexOf(".")==-1)) {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');

Is that a good way to do it?
kevin on 3 Feb 2010 says:
Hi Bill, yea, that will work as well :) well, the better way is to display error message so the user will able to know what went wrong.

for example,

if (email.val()=='') {
email.addClass('hightlight');
$('#error').html('Please enter your email');
error=1;
else if ((email.val().indexOf("@")==-1) || (email.val().indexOf(".")==-1) {
$('#error').html('Invalid Email');
error=1;
} else email.removeClass('hightlight');

of course, in your html code you'll need to create a p#error so that the error msg can be displayed. :)

Leave a comment

http://
Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons Buy and Sell Flash Buy and Sell Flash

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew

Partner

  • Web and Designers
  • CSS Style
  • PV.M Garage Blogzine - (Italian)
  • TutsValley
  • Designrfix
  • CoolVibe
  • Web Developer Juice
  • Denbagus
  • Web Hosting Secret Revealed
  • PSD to HTML Conversion
  • BlueHost