Accepting $_POSTs with AJAX / Form query

Hi,

I have the following bit of script which I’m hoping to adapt on my site.

Currently it checks one form submission and returns the data to my php page.


$(document).ready(function(){
	$("#submit").click(function(){					   				   
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/;
			
		var emailFromVal = $("#emailFrom").val();
		if(emailFromVal == '') {
			$("#emailFrom").after('<span class="error">You forgot to enter the email address to send from.</span>');
			hasError = true;
		} else if(!emailReg.test(emailFromVal)) {	
			$("#emailFrom").after('<span class="error">Enter a valid email address to send from.</span>');
			hasError = true;
		}
		
		var subjectVal = $("#subject").val();
		if(subjectVal == '') {
			$("#subject").after('<span class="error">You forgot to enter the subject.</span>');
			hasError = true;
		}
		
		var messageVal = $("#message").val();
		if(messageVal == '') {
			$("#message").after('<span class="error">You forgot to enter the message.</span>');
			hasError = true;
		}
		
		
		
		
		
		
		
		if(hasError == false) {
			$(this).hide();
			$("#sendEmail li.buttons").append('<img src="/wp-content/themes/default/images/template/loading.gif" alt="Loading" id="loading" />');
			
			$.post("/wp-content/uploads/2008/01/sendemail.php",
   				{ emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },
   					function(data){
						$("#sendEmail").slideUp("normal", function() {				   
							
							$("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');											
						});
   					}
				 );
		}
		
		return false;
	});						   
});

However, my form has three radio buttons(id = ctype) and I basically want to set it up so if:

  • ctype equals 1 then it runs the email validation check.
  • ctype equals 2 then it runs the subject check.
  • ctype equals 3, it runs the message check.

How do I go about doing this?

Many thanks for any pointers.

Shoot.

Hi Paul,

I realise this is an old issue, but it’s come back to haunt me :frowning:

Are you able to help out if I post my problem?

Thank you

Ooooft. No need. All sorted :slight_smile:

Will post how I did it shortly.

Thanks for the reply anyways, I really appreciate the offer and the help you gave previously.

The switch statement will be of help there.

Many thanks for your help.

Is there any chance you could show me how to use it in the above example. Declare the ctype variable, then the switch statement?

It’s just before I used if ~ elseif etc…, and it didn’t like that.

Would it just be:

var ctypeVal = $("#ctype").val();
switch (ctypeVal) {
case "1": 
// run if statement here
break;
case "2":
// run if statement here
etc......

?

I really do appreciate your help with this.

It looks like you’re syntax is correct.

There is an alternative as well (isn’t there always?) which is to use a lookup table for the validation type to perform.

You can place each validation section into separate functions, and then map each ctype value as the lookup key against the name of the function to run.

If you’re going to do it this way though, it’s better for the validate functions to return a positive boolean (success is positive, hasError is negative) so that it’s not confusing later on when working with them.
If hasError is used in the function, then validateEmail failed when the function returns true (confusing).
But if success is used instead, the validateEmail fails when the function returns false (better).

Here’s an example, where I’ll assign the result to hasError at the end, in what I hope is the least confusing way possible.


var validateEmail() {
    $success = true;
    var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/; 
    ...         
    return $success;
}
// other validate functions here too
...

var validateCtype = [
    '1': validateEmail,
    '2': validateSubject,
    '3': validateMessage
];
validateFn = validateCtype[ctype];
$hasError = !validateFn();

Many thanks Paul.

In your example, do I still need to declare my ctypeVal variable and assign a value to it?

I’m going to work on this a little more today.
I’ve got a feeling I may be back with 1 or 2 more questions. Hope it’s ok to reply back.

Thanks again for all your help so far, really appreciate it.

Good question - you won’t need it in my example apart from using it to decide on which function to use, so the following could also be how you use it:


var validateCtype = [
    ...
];
validateFn = validateCtype[$("#ctype").val()];

Although, for the sake of clarity I might then be tempted to rename the validateCtype variables to validationType and to use a temporary ctype variable instead.


var validationType = [
    ...
];
var ctype = $("#ctype").val();
validationFn = validationType[ctype];

Yes, you can certainly reply back. It’s a breath of fresh air for us to have someone like yourself, who is capable of making good use of the different language structures that are presented here.

Hey Paul.

I’m still a little confused by it. I’m just not sure how this will fit into my solution.

Could I possibly provide my current HTML form for you to look at too?

Thanks again for your help.

What is the confusion.

You’re welcome to provide the HTML form, but how will that help towards resolving the confusion?

Hi Paul,

Sorry, bit of a rushed reply there.

If possible, I’d like to stick with the original code when making these alts. It’s not that I don’t value your code, I really do, but it just keeps it simpler for me.
I hope you understand.

Would the following code work in my case?


$(document).ready(function(){
	$("#submit").click(function(){					   				   
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/;

var ctypeVal = $("#ctype").val();

switch (ctypeVal) {
case "1": 

		var emailFromVal = $("#emailFrom").val();
		if(emailFromVal == '') {
			$("#emailFrom").after('<span class="error">You forgot to enter the email address to send from.</span>');
			hasError = true;
		} else if(!emailReg.test(emailFromVal)) {	
			$("#emailFrom").after('<span class="error">Enter a valid email address to send from.</span>');
			hasError = true;
		}

break;
case "2":

		var subjectVal = $("#subject").val();
		if(subjectVal == '') {
			$("#subject").after('<span class="error">You forgot to enter the subject.</span>');
			hasError = true;
		}

break;
case "3":
		
		var messageVal = $("#message").val();
		if(messageVal == '') {
			$("#message").after('<span class="error">You forgot to enter the message.</span>');
			hasError = true;
		}

if(hasError == false) {
			$(this).hide();
			$("#sendEmail li.buttons").append('<img src="/wp-content/themes/default/images/template/loading.gif" alt="Loading" id="loading" />');
			
			$.post("/wp-content/uploads/2008/01/sendemail.php",
   				{ emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },
   					function(data){
						$("#sendEmail").slideUp("normal", function() {				   
							
							$("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');											
						});
   					}
				 );
		}
		
		return false;
	});						   
});

So depending on the value of ctype, it would validate different form fields.

My Form HTML:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>jQuery Ajax Forms | Trevor Davis</title>
<link href="screen.css" type="text/css" rel="stylesheet" media="screen,projection" />
<script src="http://trevordavis.net/wp-content/themes/td-v3/js/jquery.js" type="text/javascript"></script>
<script src="submitform.js" type="text/javascript"></script>
</head>

<body>

<script type="text/javascript">

function blah($this) {
	var found=null
	var els=document.getElementsByName($this.name)
	for(var i=0;i<els.length;i++){
		if(els[i]==$this){
			found=i;
			break
		}
	}
	
	if(found==0) {
		return CallBackYes()
	}
	
	if(found==1) {
		return RequestAQuoteYes()
	}
	
	if(found==2) {
		return JoinMailingListYes()
	}
	
	if(found==3) {
		return ContactUsYes()
	}
}

function CallBackYes(){
	document.getElementById("namearea").style.display="block";
	document.getElementById("telephonearea").style.display="block";
	document.getElementById("cnamearea").style.display="block";
	document.getElementById("emailarea").style.display="none";
	document.getElementById("commentsarea").style.display="none";
}

function RequestAQuoteYes(){
	document.getElementById("namearea").style.display="block";
	document.getElementById("emailarea").style.display="block";
	document.getElementById("cnamearea").style.display="block";
	document.getElementById("commentsarea").style.display="none";
	document.getElementById("telephonearea").style.display="none";
}

function JoinMailingListYes(){
	document.getElementById("namearea").style.display="block";
	document.getElementById("emailarea").style.display="block";
	document.getElementById("cnamearea").style.display="block";
	document.getElementById("commentsarea").style.display="none";
	document.getElementById("telephonearea").style.display="none";
}

function ContactUsYes(){
	document.getElementById("namearea").style.display="block";
	document.getElementById("telephonearea").style.display="block";
	document.getElementById("cnamearea").style.display="block";
	document.getElementById("emailarea").style.display="block";
	document.getElementById("commentsarea").style.display="block";
}

</script>

<div id="container">
<?php include('verify.php'); ?>
	<form action="index.php" method="post" id="sendEmail">
		<fieldset style="background:#eaeaea">

    <legend>Options</legend>
    
    <input type="radio" id="ctype" name="ctype" value="1" onclick="blah(this)" />Call me back<br />
    <input type="radio" id="ctype" name="ctype" value="2" onclick="blah(this)" />Request a Quote<br />
    <input type="radio" id="ctype" name="ctype" value="3" onclick="blah(this)" />Join Mailing List<br />
    <input type="radio" id="ctype" name="ctype" value="4" onclick="blah(this)" />Contact Us<br /><br />
    
    <div id="namearea" style="display: none;">
    <label for="uname">Name</label><br />
    <input type="text" name="uname" id="uname" /><br /><?php if(isset($unameError)) echo '<span class="error">'.$unameError.'</span>'; ?><br />
    </div>
    
    <div id="telephonearea" style="display: none;">
    <label for="telnum">Telephone</label><br />
    <input type="text" name="telnum" id="telnum" /><br /><?php if(isset($telnumError)) echo '<span class="error">'.$telnumError.'</span>'; ?><br />
    </div>
    
    <div id="emailarea" style="display: none;">
    <label for="emailFrom">Email</label><br />
    <input type="text" name="emailFrom" id="emailFrom" /><br /><?php if(isset($emailFromError)) echo '<span class="error">'.$emailFromError.'</span>'; ?><br />
    </div>
    
    <div id="cnamearea" style="display: none;">
    <label for="cname">Company Name</label><br />
    <input type="text" name="cname" id="cname" /><br /><?php if(isset($cnameError)) echo '<span class="error">'.$cnameError.'</span>'; ?><br />
    </div>
    
    <div id="commentsarea" style="display: none;">
    <label for="">Comments</label><br />
    <textarea id="comments" name="comments"></textarea><br /><?php if(isset($commentsError)) echo '<span class="error">'.$commentsError.'</span>'; ?><br />
    </div>
    
    <button type="submit" id="submit">Send Email &raquo;</button><input type="hidden" name="submitted" id="submitted" value="true" />
    
    </fieldset>
    	
	</form>
	<div class="clearing"></div>
</div>

</body>
</html>

Thanks again for any help with this.

The technique should work well.

Don’t forget about including a default case in the switch, to handle unexpected ctype entries.

Wow, scary thing is, it’s working :slight_smile:
I may be back later today. Hopefully not too soon.

Thanks again for your patience and help Paul, very much appreciated.

Hmm, I’ve got a problem.

It seems to run case “1”: even when my ctypeVal equals 2.

Can you think why it would do this?

From the posted code I see no reason why it would do that.

The only rational explanation is that during further editing of the code, a break statement was missed out.

An examination of the live-site code would help to clear up this issue.

Hi Paul,

Many thanks.

Here we go: http://bit.ly/biZD6P

Thanks again for any pointers

I suspect that you’re wanting to protect yourself in some way, but please be aware that url shortening/disguising technique can be grounds for action against your account. It’s a policy put in place relating to spammers, but I wouldn’t want to see you bitten by it.

Next time, please consider sending it via a personal message instead, if you don’t want to post the full url.

Paul, I’m very sorry. Am I ok to PM this to you? I would’ve, but didn’t want to be seen to pester you.

Again, my apologies, I didn’t realise this was frowned on.

Can you please help to clarify the expected behaviour for both ctype of 1 and for 2