?
Solved

JavaScript form validation works but form does not submit

Posted on 2011-09-13
3
Medium Priority
?
430 Views
Last Modified: 2012-05-12
I have a pretty basic javascript form validator that catches all of the proper validations, but when everything is correct, it fails to submit the script.

Am I missing something obvious?

I have provided the code below - here is a link to the dev page:
http://63.250.226.15/olivet/index.php?purl=TylerSample3

Thanks - Bill
<?php

$p = $_REQUEST['purl'];

$purl = preg_replace('/[^A-Za-z0-9]/','',$p); 


require_once 'config.php';

if ($conn = mysql_connect($db['host'], $db['user'], $db['pass'])) {
        mysql_select_db($db['database'], $conn);
        if($config['debug'] == "true") {
          echo 'Connection established...<br>';
        }
}

if($_REQUEST['s'] == "yes"){
	$fname = mysql_real_escape_string($_REQUEST['firstname']);
	$lname = mysql_real_escape_string($_REQUEST['lastname']);
	$email = mysql_real_escape_string($_REQUEST['emailaddress1']);
	$phone = mysql_real_escape_string($_REQUEST['phone']);
	$grad_year = mysql_real_escape_string($_REQUEST['HSGradYear']);
	$visit = $_REQUEST['date1'];
	$optin = mysql_real_escape_string($_REQUEST['donotemail']);
	$prog = $_REQUEST['prog'];
	
	if ($prog == "f"){
                $header = "ONU_FlyMobile.jpg";
        }else{
                $header = "ONU_OurGuestMobile.jpg";
        }
	

	$query = 'UPDATE olivet_students SET fname="'.$fname.'",lname="'.$lname.'",email="'.$email.'",phone="'.$phone.'",grad_year="'.$grad_year.'",visit="'.$visit.'",opt-in="'.$optin.'" WHERE purl="'.$purl.'"';

	$result = mysql_query($query, $conn);

	$to      = 'boconnell@libertycreativesolutions.com';
	$subject = 'Student Request for Visit';
	if($prog == "f"){
		$message = "The following Student has requested a visit with the Free Flight option:\n\n";
	}else{
		$message = "The following Student has requested a visit via personal transportation:\n\n";
	}
	$message .= "Name:".$fname ." ".$lname."\nEmail:".$email."\nPhone:".$phone."\nHS Grad Year:".$grad_year."\nRequested Visit Date:".$visit;
	if($optin == "true"){
		$message .= "\n\nThis student has OPTED IN to email communications";
	}else{
		$message .= "\n\nThis student has OPTED OUT of email communications";
	}
	$headers = 'From: boconnell@libertycreativesolutions.com' . "\r\n" .
    		'Reply-To: boconnell@libertycreativesolutions.com' . "\r\n" .
    		'X-Mailer: PHP/' . phpversion();

	mail($to, $subject, $message, $headers);

?>

	<!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" xml:lang="en" lang="en">
	<head>
	    <meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport" />
	    <meta name="HandheldFriendly" content="true" />
	    <title>Olivet Nazarene University</title>
	

	</head>
	<body style="background-color: #654972; color: #ffffff; font-family: arial,sans-serif;">

                        <div id="header">
                               <img src="<?php echo $header; ?>" width=300px />
                        </div>



    			<div id="pageCt">

                                        <div id="pageTitle">
                                                <h2>Visit Request Sent</h2>
                                        </div>

			<p>Thank you <?php echo $fname; ?>,</p>

				<p>Your visit request has been submitted and you will be contacted shortly to finalize your arrangments.</p>

			<br /><p>Sincerely,<br />The Olivet Nazarene Admissions Staff</p>

			

			</div>
	</body>
	</html>
<?php		
	
}else{

	$query = 'SELECT fname,lname,email,purl,phone,grad_year,program from olivet_students WHERE purl="'.$purl.'"';
                $result = mysql_query($query, $conn);
                if (!$result) {
                        if($config['debug'] == "true") {
                                $message  = 'Invalid query: ' . mysql_error() . "\n";
                                $message .= 'Whole query: ' . $query;
                                $message .= '<br>';
                                die($message);
                        }
                }
                while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
                        $fname = $row['fname'];
                        $lname = $row['lname'];
                        $phone = $row['phone'];
                        $email = $row['email'];
			$purl = $row['purl'];
			$sid = $row['sid'];
                        $grad_year = $row['grad_year'];
                        $prog = $row['program'];
		}

	if ($prog == "f"){
        	$header = "ONU_FlyMobile.jpg";
	}else{
        	$header = "ONU_OurGuestMobile.jpg";
	}


	$years = array("2018","2017","2016","2015","2014","2013","2012","Other");

?>

<!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" xml:lang="en" lang="en">
<head>
    <meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport" />
    <meta name="HandheldFriendly" content="true" />
    <title>Olivet Nazarene University</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>

    <script src="js/jquery.scroller-1.0.2.js" type="text/javascript"></script>

    <link rel="stylesheet" type="text/css" href="css/jquery.scroller-1.0.2.css" />

    <script type="text/javascript">
        $(document).ready(function () {
            $('#date1').scroller();
            $('#date2').scroller({ preset: 'time' });
            $('#date3').scroller({ preset: 'datetime',
                seconds: true,
                ampm : false,
                dateOrder: 'dMyy',
                theme: 'sense-ui'
            });
            wheels = [];
            wheels[0] = { 'Hours': {} };
            wheels[1] = { 'Minutes': {} };
            for (var i = 0; i < 60; i++) {
                if (i < 16) wheels[0]['Hours'][i] = (i < 10) ? ('0' + i) : i;
                wheels[1]['Minutes'][i] = (i < 10) ? ('0' + i) : i;
            }
            $('#custom').scroller({
                width: 90,
                wheels: wheels,
                formatResult: function (d) {
                    return ((d[0] - 0) + ((d[1] - 0) / 60)).toFixed(1);
                },
                parseValue: function (s) {
                    var d = s.split('.');
                    d[0] = d[0] - 0;
                    d[1] = d[1] ? ((('0.' + d[1]) - 0) * 60) : 0;
                    return d;
                }
            });
            $('#disable').click(function() {
                if ($('#date2').scroller('isDisabled')) {
                    $('#date2').scroller('enable');
                    $(this).text('Disable');
                }
                else {
                    $('#date2').scroller('disable');
                    $(this).text('Enable');
                }
                return false;
            });

            $('#get').click(function() {
                alert($('#date2').scroller('getDate'));
                return false;
            });

            $('#set').click(function() {
                $('#date2').scroller('setDate', new Date(), true);
                return false;
            });

        });


     </script>

     <script type="text/javascript">

	function formValidator(){
		// Make quick references to our fields
		var firstname = document.getElementById('firstname');
		var lastname = document.getElementById('lastname');
		var email = document.getElementById('emailaddress1');
		var email_confirm = document.getElementById('emailaddress1_confirm');
		var phone = document.getElementById('phone');
		var year = document.getElementById('HSGradYear');
		var visit = document.getElementById('date1');
		
		// Check each input in the order that it appears in the form!
		if(notEmpty(firstname,"First Name Required")){
			if(notEmpty(lastname,"Last Name Required")){
				if(emailValidator(email,"Invalid Email Address")){
					if(emailMatch(email,email_confirm,"Email Addresses do not Match")){
						if(isPhone(phone,"Use Valid Phone number")){
							if(madeSelection(year,"Choose Graduation Year")){
								if(madeSelection(visit,"Choose Date of Visit")){
									return true;
								}
							}
						}
					}
				}
			}
		}
		
	}	
	function notEmpty(elem, msg){
		if(elem.value.length == 0){
			alert(msg);
			elem.focus(); // set the focus to this input
			return false;
		}else{
		return true;
		}
	}

	function isPhone(elem, msg){
		var numericExpression = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
		if(elem.value.match(numericExpression)){
			return true;
		}else{
			alert(msg);
			elem.focus();
			return false;
		}
	}


	function emailValidator(elem, msg){
		var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
		if(elem.value.match(emailExp)){
			return true;
		}else{
			alert(msg);
			elem.focus();
			return false;
		}
	}


        function emailMatch(elem,elem2, msg){
                if(elem.value == elem2.value){
                        return true;
                }else{
                        alert(msg);
                        elem.focus();
                        return false;
                }
        }


function madeSelection(elem, msg){
	if(elem.value == "Choose Your HS grad Year" || elem.value == ""){
		alert(msg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}



     </script>

</head>
<body style="background-color: #654972; color: #ffffff; font-family: arial,sans-serif;">

			<div id="header">
                               <img src="<?php echo $header; ?>" width=300px />
                        </div>



    <div id="pageCt">

                                        <div id="pageTitle">
                                                <h2>Request a Visit</h2>
                                        </div>

        <form name="mForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="mForm" onSubmit="return formValidator(this)" >
	<input type="hidden" name="prog" value="<?php echo $prog; ?>" />
	<input type="hidden" name="s" value="yes" />


				<div id="zone1"><table border="0"><tr>

                    				
                                                        <td><label for="firstname">
                                                            First Name<span>*</span>
                                                        </label></td>

                                                        <td><input name="firstname" type="text" id="firstname" value="<?php echo $fname; ?>" />
                                                        </td>

							</tr><tr>

                                                        <td><label for="lastname">
                                                            Last Name<span>*</span>
                                                        </label></td>

                                                        <td><input name="lastname" type="text" id="lastname" value="<?php echo $lname; ?>" />
                                                        </td>
                                                            
							</tr><tr>

                                                        <td><label for="emailaddress1">
                                                            E-mail Address<span>*</span>
                                                        </label></td>

							<td><input name="emailaddress1" type="text" id="emailaddress1" value="<?php echo $email; ?>" />
                                                        </td>

							</tr><tr>
                                                                                        
                                                        <td><label for="emailaddress1_confirm">
                                                            Confirm E-mail Address<span>*</span>
                                                        </label></td>

                                                        <td><input name="emailaddress1_confirm" type="text" id="emailaddress1_confirm" value="<?php echo $email; ?>" />
                                                        </td>

							</tr><tr>

                                                        <td><label for="donotemail">
                                                            May we contact you via E-mail?
                                                        </label></td>

                                                        <td><input name="donotemail" type="checkbox" id="donotemail" checked="checked" value="true" /></td>

							</tr><tr>

                                                        <td><label for="phone">Phone Number<span>*</span></label></td>

                                                        <td><input name="phone" type="text" id="phone" value="<?php echo $phone; ?>" />
                                                    	</td>

							</tr><tr>
                                                                         
                                                        <td><label for="HSGradYear">High School Grad Year:</label></td>

                                                        <td><select name="HSGradYear" id="HSGradYear">
								<option value="">Choose Your HS grad Year</option>
					
				<?php
					$tagged = 0;
					foreach($years as $year){
						if($year == $grad_year){
							echo '<option selected value="'.$year.'">'.$year.'</option>';
							$tagged++;
						}else{
							echo '<option value="'.$year.'">'.$year.'</option>';
						}
					}
						
					if($tagged == 0){
						echo '<option selected value="">Choose Your HS grad Year</option>';
					}

				?>
							</select>
                                                     	</td>

							</tr><tr>

							<td><div data-role="fieldcontain">
                    						<label for="date1">Choose Date for your Visit</label></td>
                    <td><input type="text" name="date1" id="date1" class="genField textEntry date" readonly="readonly" value="" />
                </div>
                                                     	</td>
			</tr><tr>

                                 <td><input type="submit" name="mSubmit" value="Submit" id="mSubmit"  /></td><td>&nbsp;</td>
				</tr></table></div>
        

			</form>
	</div>
		<div id="footer"><p>

			    
		</p>
		</div>
</body>
</html>

<?php
}
?>

Open in new window

0
Comment
Question by:jabberwok_e
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 4

Assisted Solution

by:Somersault
Somersault earned 400 total points
ID: 36530511
When changing this:
onSubmit="return formValidator(this)"

To:
onSubmit="alert(formValidator(this));"

You can see that the validator works, problem is that it's not submitting the action properly.

I believe the problem you are experiencing is because you're missing one line of code in your formValidator() function. In the bottom of that function you need to add: return false;

Without it it won't work properly. Because it needs a return value inside the function that is not inside any if-conditionals or the like.

So your function should look something like this:
	function formValidator(){
		// Make quick references to our fields
		var firstname = document.getElementById('firstname');
		var lastname = document.getElementById('lastname');
		var email = document.getElementById('emailaddress1');
		var email_confirm = document.getElementById('emailaddress1_confirm');
		var phone = document.getElementById('phone');
		var year = document.getElementById('HSGradYear');
		var visit = document.getElementById('date1');
		
		// Check each input in the order that it appears in the form!
		if(notEmpty(firstname,"First Name Required")){
			if(notEmpty(lastname,"Last Name Required")){
				if(emailValidator(email,"Invalid Email Address")){
					if(emailMatch(email,email_confirm,"Email Addresses do not Match")){
						if(isPhone(phone,"Use Valid Phone number")){
							if(madeSelection(year,"Choose Graduation Year")){
								if(madeSelection(visit,"Choose Date of Visit")){
									return true;
								}
							}
						}
					}
				}
			}
		}
	
		return false;
	}

Open in new window


See that last return false; ? You need to add it to all your form-check functions that returns a value.

That should make it work!

Cheers,
Chris
0
 
LVL 13

Accepted Solution

by:
ansudhindra earned 1600 total points
ID: 36530820
@Chris, your suggestion didnt worked (for me)...

@Jabber
specify the argument in the function definition. currently it is

function formValidator(){

change it to

function formValidator(ele){

and in the code
change from

if(madeSelection(visit,"Choose Date of Visit")){
 return true;
}

to

if(madeSelection(visit,"Choose Date of Visit")){
ele.submit();      
return true;
}

and also, add "return false;" before the close of the function call.
0
 

Author Comment

by:jabberwok_e
ID: 36531079
Thank you guys -

ansudhindra's solution did the trick!
0

Featured Post

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
A big percent of today’s marketing activity is performed through the online environment. The marketing strategies that have existed a decade ago no longer relate to what’s happening today. We’re currently facing a revolutionary era, called the digit…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question