I'm validating a form using the JQuery validation plugin.
The very first time the page loads, the form is validated perfectly and only submits once all fields have been completed. The form then posts back to itself and when trying to enter details again, the validation does not work but still allows to submit and the data gets successfully sent to the database.
Here is my code:
<form id="formSubmit" method="post" action="post to this page">
<fieldset data-role="fieldcontain">
<p>
<label for="clubSelect">Preferred Club</label>
<select id="clubSelect" name="clubSelect" class="required">
<option value="000">Select a Club</option>
<?php if ($db->num_rows > 0)
{
foreach($results as $result)
{
?>
<option value="<?php echo $result->id;?>"><?php echo $result->name;?></option>
<?php
}
}
?>
</select>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtName">Name</label>
<input type="text" id="txtName" name="txtName" class="required"/>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtEmail">Email</label>
<input type="text" id="txtEmail" name="txtEmail" class="required email" minlength="5"/>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtCell">Contact Number</label>
<input type="tel" id="txtCell" name="txtCell" class="required"/>
</fieldset>
<fieldset data-role="fieldcontain">
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
<script>
$(document).ready(function () {
$("#formSubmit").validate({
rules: {
clubSelect: {
selectcheck: true
},
txtName: {
required: true
},
txtEmail: {
required: true
},
txtCell: {
required: true,
number: true
}
},
messages: {
txtName: {
required: "Please enter your name."
},
txtEmail: {
required: "Please enter your email address."
},
txtCell: {
required: "Please enter your contact number.",
number: "Only numbers are allowed."
}
}
});
jQuery.validator.addMethod('selectcheck', function (value) {
return (value != '000');
}, "Please select a club.");
});
</script>
Basically what I am asking is how to make sure that the validation always works.
Thanks
Replace
$(document).ready(function ()
with
$('#pagID').on('pageshow', function () {
Update: Also, add data-ajax=false to the form div, to avoid posting data using Ajax.
jQuery Mobile Events
Why not to use .ready
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a username form. Which have 2 fields, username and password.
Basically I want it so if the user has not entered the fields and pressed 'submit' an error displays like
"Please enter the required fields"
I know it's possible with JavaScript or PHP but unsure how to do it.
Here is the code of the user and password form:
<div id="sessionContainer" class="clearfix">
<div class="content">
<form action="goto.php" class=" sign-in" method="post">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" />
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" />
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="submit" tabindex=5>Sign in</button>
</p>
Thanks
<?php if(!isset($_POST['email']) || !isset($_POST['password'])
This code will check if either of those fields has a value. If it does not, you can output an error message. The code in the whole context is as follows:
<?php if(!isset($_POST['email']) || !isset($_POST['password']): ?>
<div>Please fill in all fields!</div>
<?php endif; ?>
This is my answer...in clasic javascript xD:
<html>
<head>
<script type="text/javascript">
function validar()
{
var right = 1;
if(document.getElementById('email').value.length==0)
{
right = 0;
document.getElementById('emptymail').innerHTML = "Empty Mail o Username";
}
if(document.getElementById('password').value.length==0)
{
right = 0;
document.getElementById('emptypass').innerHTML = "Empty Password";
}
if(right == 1)
{
document.forms["formu"].submit();
}
}
</script>
</head>
<body>
<form action="goto.php" class=" sign-in" method="post" name="formu" id="formu">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" /><div id="emptymail"></div>
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" /><div id="emptypass"></div>
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="button" tabindex=5 onclick="validar();">Sign in</button>
</p>
</form>
</body>
</html>
Saludos ;)
HTML only solution using the required attribute (works only in newer browsers):
<input required="required" />
An example how to do a jscript based solution can be found here, here or this one with a little jquery help.
Use jQuery Validate for validations
Download it from here and call it. and then add this code
rules:
{
email:
{
required: true
}
},
messages:
{
email:
{
required: "Please enter your email."
}
}
OR simply Use HTML 5 validations
<input id="email" name="email" type="text" value="" required />
To do it using JavaScript, you are looking for the OnSubmit attribute of your form
There are numerous things you can do if the function you called with OnSubmit fails (returns false), but as an example this code will show a popup box
<script>
function checkForm()
{
if (document.getElementById('email').value.length==0 || document.getElementById('password').value.length==0)
(
alert("fill in required fields")
return false;
)
return true;
}
<script>
Then in your form tag you put
<form onsubmit="return checkForm()" ...
var $form = $('form'),
$user = $('#email),
$pass = $('#password');
$form.on('submit', function(e) {
e.preventDefault(); // stop the default behavior
if ($user.text().length === 0) {
$user.addClass('error'); // do something with the error class or add attribute 'required'
} else if ($pass.text().length === 0) {
// do something else
} else if ($user.text().length > 0 && $pass.text().length > 0) {
// post the form
$.ajax({
url: //URL where you send,
data: $form.serialize(),
success: function(e) { // do something },
error: function(e) { // do something }
});
}
}
I am still learning PHP, so bear with me. I am trying to create a sign up form that includes 2 DIVs. Once you click submit on the first div (personal info), it slides away and the second div (billing info) slides up using jQuery.
My problem is... I need some help figuring out how to determine if the submit function came from the first div or the second. If it's the first div, the slide happens. If it's the second div, the form is submitted.
HTML with Form
<div id="container">
<!-- #first_step -->
<div id="first_step">
<h1>SIGN UP FOR 17 FIT CLUB</h1>
<form class="signup" action="post/signup" method="post">
<input type="hidden" name="step" value="user" />
<div class="form">
<input type="text" name="email" id="email_signup" value="" />
<label for="email">Your email address. We send important administration notices to this address. </label>
<input type="text" name="confirmemail" id="cemail_signup" value="" />
<label for="username">Please re-type your email to verify it is correct.</label>
<input type="text" name="firstname" id="firstname_signup" value="" />
<label for="firstname">Your First Name. </label>
<input type="text" name="lastname" id="lastname_signup" value="" />
<label for="lastname">Your Last Name. </label>
<input type="text" name="username" id="username_signup" value="" />
<label for="username">At least 6 characters. Uppercase letters, lowercase letters and numbers only.</label>
<input type="password" name="password" id="password_signup" value="" />
<label for="password">At least 6 characters. Use a mix of upper and lowercase for a strong password.</label>
<input type="password" name="cpassword" id="cpassword_signup" value="" />
<label for="cpassword">If your passwords aren’t equal, you won’t be able to continue with signup.</label>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="submit" type="submit" name="submit_first" id="submit_first" value="submit"/>
</form>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<!-- #second_step -->
<div id="second_step">
<h1>SIGN UP FOR 17 FIT CLUB</h1>
<form class="signup" action="post/signup" method="post">
<input type="hidden" name="step" value="user" />
<div class="form">
<input type="text" name="nameoncard" id="nameoncard_signup" value="" />
<label for="email">Enter the name on the credit or debit card used for billing. </label>
<select name="cardtype" id="cardtype_signup" >
<option name="visa">Visa</option>
<option name="mastercard">Mastercard</option>
<option name="amex">American Express</option>
<option name="discover">Discover</option>
</select>
<label for="cardtype">What type of card are you using?</label>
<input type="text" name="cardnumber" id="cardnumber_signup" value="" />
<label for="cardnumber">Enter the card number.</label>
<div id="exp_date_signup">
<select name="exp_month" id="exp_month_signup" >
<option name="01">01</option>
<option name="02">02</option>
<option name="03">03</option>
<option name="04">04</option>
</select>
<select name="exp_year" id="exp_year_signup" >
<option name="12">12</option>
<option name="13">13</option>
<option name="14">14</option>
<option name="15">15</option>
</select>
</div>
<label for="exp_year">Enter the expiration date on the card.</label>
<input type="text" name="CVV2" id="cvv2_signup" value="" />
<label for="CVV2">Enter the 3 or 4 digit CVV2 number.</label>
<select name="country" id="country_signup">
<option value=" " selected>(please select a country)</option>
<option value="AF">Afghanistan</option>
<option value="ZM">...More options...</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="country">Enter the country for your billing address.</label>
<input type="text" name="billingaddress" id="billingaddress_signup" value="" />
<label for="bilingaddress">Enter the street name and number for the credit or debit card billing address.</label>
<input type="text" name="billingcity" id="billingcity_signup" value="" />
<label for="billingcity">Enter the city for you billing address.</label>
<select name="billingstate" id="billingstate_signup">
<option value="AL">Alabama</option>
<option value="AK">...More options...</option>
<option value="WY">Wyoming</option>
</select>
<label for="billingstate">Choose the state for your billing address.</label>
<input type="text" name="billingpostalcode" id="billingpostalcode_signup" value="" />
<label for="cpassword">Enter the postal code for your billing address.</label>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="send submit" type="submit" name="submit_second" id="submit_second" value="submit" />
</form>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
</div>
Javascript (I put "???" in the area I assume I need help)
<script type="text/javascript">
$(function(){
$('form.signup').submit(function(event){
event.preventDefault();
uri = $(this).attr('action');
data = $(this).queryString();
$.get(uri, data, function(response){
if(response.status == 0){
alert(response.message);
}
else if(???){
//show next step
$('#first_step').slideUp();
$('#second_step').slideDown();
}
else {
// redirect to internal home page
window.location = '<?=PROTOCOL?>//<?=DOMAIN?>/home';
}
}, 'json');
});
$('form.signup input').focus(function(event){
if(!$(this).hasClass('clicked')){
$(this)
.val('')
.addClass('clicked');
}
});
});
</script>
Any help would be greatly appreciated! I am sure this has a simple solution, but I haven't been able to crack it. n00b!
UPDATE:
ANSWER LISTED BELOW
What I would recommend is to combine both of the forms into only one form; split up the two "forms" with div tags with two separate buttons and then have jquery like this
//First Button Click Handler
$.("form div#first input.submit").click(function(){
$("div.first").slideUp('fast',function(){
$("div.second").slideDown('fast');
});
});
//Second Button Click Handler
$.("form div#second input.submit").click(function(){
var data = $('form').serialize();
var url = "whatever";
$.get(url,data,function(response){
//Handle Response
});
});
The trick is to disable the form's normal submit triggers and then handle them directly using specific click handlers
Something like this in the html will stop your form submitting by default
<form onsubmit="return false;">
<input type="password"/>
<input type="submit"/>
</form>
Have a next button that calls the jQuery function and the submit button at the bottom of the billing info. Ex:
function(slide){
$('#first_step').slideUp();
$('#second_step').slideDown();
}
Here is the answer to my question. I figured it out with the assistance of a person in RL. Both submit inputs have their own value, "user" and "billing" respectively.
<script type="text/javascript">
$(function(){
$('form.signup').submit(function(event){
event.preventDefault();
uri = $(this).attr('action');
data = $(this).queryString();
step = $(this).find('input[name=step]').val(); // <--update
if(response.status == 0){
alert(response.message);
}
else{ // <--update
if(step == 'user'){ // <--update
//show next slide // <--update
$('#first_step').slideUp(); // <--update
$('#second_step').slideDown(); // <--update
} // <--update
else if(step == 'billing'){ // <--update
//redirect to internal home page // <--update
window.location = '<?=PROTOCOL?>//<?=DOMAIN?>/home'; // <--update
} // <--update
}
}, 'json');
});
$('form.signup input').focus(function(event){
if(!$(this).hasClass('clicked')){
$(this)
.val('')
.addClass('clicked');
}
});
});
</script>
I am working on a form that will be validated in Javascript and then, if it is valid, proceed to a PHP submission. The PHP is working fine and will not allow a submission if the input isn't valid. However, I can't get the form to stop before going to the PHP page if the validation function returns as false. Does anyone know what I can do to make this work?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Form</title>
<script src="contact.js" type="text/javascript"> </script>
</head>
<body>
<form name="contact"id="contact" action="contact.php" onsubmit="return formSub();"method="post" >
<h2 class="headingText"><em>What's your name?</em></h2>
<p>
<label for="firstName">First Name </label>
<input type="text" name="firstName" id="firstName" tabindex="7">
<span id="firstNameHTML" class="error"> </span>
</p>
<p>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" tabindex="8">
<span id="lastNameHTML" class="error"> </span>
</p>
<p> </p>
<h2 class="headingText"><em>What's your preferred email address?</em></h2>
<p>
<label for="email">Email Address</label>
<input type="text" name="email" id="email" tabindex="9">
<span id="emailHTML" class="error"> </span>
</p>
<p> </p>
<h2 class="headingText"><em>What would you like to contact us about?</em><br><span id="interestHTML"></span>
</h2>
<p>
<label>
<input type="checkbox" name="Interest" value="training" id="Interest_training" tabindex="10">
Training Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="testing" id="Interest_testing" tabindex="11">
Testing Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="remediation" id="Interest_remediation" tabindex="12">
Remediation Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="General Question" id="Interest_general" tabindex="13">
General Question</label>
<br>
<label>
<input type="checkbox" name="Interest" value="error" id="Interest_error" tabindex="14">
Report a Website Error</label>
<br>
<label>
<input type="checkbox" name="Interest" value="other" id="Interest_other" tabindex="15">
Other</label>
</p>
<p>
<label for="comment"><span class="headingText">Please enter your question or comments here. </span></label><br>
<span id="commentHTML"></span>
<textarea name="comment" id="comment" cols="45" rows="5" width="100px" tabindex="16"></textarea>
</p>
<input name="submit" type="submit" value="Submit the Form" tabindex="17">
<input name="reset" type="reset" value="Reset the Form" tabindex="18">
</form>
<p> </p>
<p> </p>
</body></html>
Javascript Document:
// JavaScript Document
function checkForm()
{
formReset();
var error=0;
//Check firstName has value
if (document.getElementById("firstName").value=="")
{
document.getElementById("firstNameHTML").innerHTML="<strong> Please provide a first name</strong>";
error++;
if(error==1)
{
document.getElementById("firstName").focus();
}
}
//Check lastName has value
if (document.getElementById("lastName").value=="")
{
document.getElementById("lastNameHTML").innerHTML="<strong> Please provide a last name</strong>";
error++;
if(error==1)
{
document.getElementById("lastName").focus();
}
}
//Check email is valid
if (document.getElementById("email").value=="" || document.getElementById("email").value.search("#") < 0)
{
document.getElementById("emailHTML").innerHTML="<strong> Please provide a valid email address</strong>";
error++;
if(error==1)
{
document.getElementById("email").focus();
}
}
//Check Interest has value
if (document.getElementByName("Interest").value=="")
{
document.getElementById("InterestHTML").innterHTML="<strong> Please let us know what you are interested in contacting us about.</strong>";
error++;
}
//Check Comment has value
if (document.getElementById("comment").value=="")
{
error++;
document.getElementById("commentHTML").innerHTML="<strong> Please provide your questions or comments here</strong><br>";
if(error==1)
{
document.getElementById("comment").focus();
}
}
if (error==0)
{
alert("Passed");
return true;
}
alert("Failed");
return false;
}
function formReset(){
document.getElementById("firstNameHTML").innerHTML="";
document.getElementById("lastNameHTML").innerHTML="";
document.getElementById("emailHTML").innerHTML="";
alert("Reset");
}
function formSub(){
if(checkForm())
{
alert("Check is True");
document.getElementById("contact").submit();
return true;
}
alert("I'm sorry, your submission cannot be completed.");
return false;
}
You should do:
onsubmit="return formSub();"
delete javascript:
If your function returns false the form wont be submitted.
You have made a mistake on checkForm function. getElementsByName returns an array of elements. So, in order to check if all of them are unchecked, you have to replace the code with this:
//Check Interest has value
var interests = document.getElementsByName("Interest");
var noneChecked = true;
for(var i = 0; i < interests.length; i++) {
if (interests[i].checked) {
noneChecked = false;
}
}
if (noneChecked) {
document.getElementById("interestHTML").innterHTML="<strong> Please let us know what you are interested in contacting us about.</strong>";
error++;
}
Then your function will work as you wanted.
Having trouble getting a form using PHP, JQuery Form plugin, and JQuery Validate plugin to work as expected. I'm using Validation plugin v 1.8.1, so it is not due to the bug with dataType: 'json', being read as jsonp. Below is the html:
<?php require_once('includes/initialize.php'); ?>
<?php require_once('layouts/header.php'); ?>
<body>
<div class="container_12">
<div class="grid_4" id="form">
<form action="actions/register.php" method="POST" class="cmxform" name="frmPrntRgstr" id="frmPrntRgstr">
<p>
<label>Desired Username:</label>
<input type="text" name="userName" id="userName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Password:</label>
<input type="password" name="Pwd" id="Pwd" />
</p>
<p>
<label>Confirm Password:</label>
<input type="password" name="confirmPwd" id="confirmPwd" />
</p>
<div class="clear"></div>
<p>
<label>First Name:</label>
<input type="text" name="firstName" id="firstName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Last Name:</label>
<input type="text" id="lastName" name="lastName" value="" />
</p>
<div class="clear"></div>
<p>
<label>Email Address:</label>
<input type="text" id="email" name="email" value="" />
</p>
<div class="clear"></div>
<p>
<label>Cell Phone:</label>
<input type="text" id="cellPhone" name="cellPhone" value="" />
</p>
<p>
<label>Home Phone:</label>
<input type="text" id="homePhone" name="homePhone" value="" />
</p>
<input type="hidden" id="role" name="role" value="2" />
<input type="hidden" id="approved" name="approved" value="0" />
<input type="hidden" id="school" name="school" value="0" />
<p>
<input class="submit" type="submit" id="regUser" value="Submit" />
</p>
</form>
<p id="frmPrntRgstrRspns" style="display: none;">A Response goes here.</p>
</div>
</div>
Simplified version of register.php without error checking:
<?php require_once('../includes/initialize.php'); ?>
<?php require_once('../layouts/appheader.php'); ?>
<?php
if (isset($_POST["userName"])) {
$auser = new User();
$auser->userName = $_POST['userName'];
$auser->hshdPwd = sha1($_POST['Pwd']);
$auser->firstName = $_POST['firstName'];
$auser->lastName = $_POST['lastName'];
$auser->email = $_POST['email'];
$auser->cellPhone = $_POST['cellPhone'];
$auser->homePhone = $_POST['homePhone'];
if(!is_null($_POST['school'])) {
$auser->school = $_POST['school'];
} else {
$auser->school = "0";
}
$auser->prelim_role = $_POST['role'];
$auser->approved = $_POST['approved'];
if($auser->create()) {
$abc = array('response'=>"Request successfully submitted"); ;
} else {
$abc = array('response'=>"Errors.");
}
return ?>
<script type="text/javascript">
var resp2 = '<?php echo json_encode($abc, JSON_FORCE_OBJECT); ?>';
</script>
<?php
}
?>
Below is the register.js file:
$(document).ready(function() {
$("#frmPrntRgstr").validate({
rules: {
firstName: "required",
lastName: "required",
userName: {
required: true,
minlength: 6
},
Pwd: {
required: true,
minlength: 6
},
confirmPwd: {
required: true,
minlength: 6,
equalTo: '#Pwd'
},
homePhone: {
required: true,
},
cellPhone: {
required: true,
},
email: {
required: true,
email: true
},
},
messages: {
firstName: "Please enter your firstname",
lastName: "Please enter your lastname",
userName: {
required: "Please enter a username",
minlength: "Your username must consist of at least 6 characters"
},
hshdPwd: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long"
},
confirmPwd: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function(form) {
$("#frmPrntRgstr").ajaxSubmit({
dataType: 'json',
success: processJson,
})
}
});
function processJson() {
var resp3 = $.parseJSON(resp2);
$("#frmPrntRgstr").slideUp("normal", function() {
$(resp3.response).appendTo("#frmPrntRgstrRspns", function() {
$("#frmPrntRgstrRspns").slideDown("normal");
})
})
}
});
I have tried changing content type to "application/json" in all files. When I remove dataType: 'json' and have a success function like $("#frmPrntRgstr").slideUp("normal", function () { $("#frmPrntRgstrRspns").slideDown("normal") }); everything works fine. When I add dataType: 'json', even when I'm not trying to parse the json server response or use it in the success function, the new user will be inserted into the MySQL database, but the client-side sees no response. Any help would be greatly appreciated.
This is what your script returns:
<script type="text/javascript">
var resp2 = '<?php echo json_encode($abc, JSON_FORCE_OBJECT); ?>';
</script>
This is not JSON, it's a fragment of HTML that contains a script tag with a javascript variable declared inside of it.
A JSON response would look like <?php echo json_encode($abc); ?> alone.
Thank you for your time, I have spent a good part of my day googling every way I can think of and I cant find a clear simple answer. Ive tried everything I can think of and have found great answers here. I sure hope someone can help me. Ive done most of my research on jquery on there site and to no avail I'm still looking for answers. Ive found some help full articles here also, I just must not be fully understanding or am overlooking some simple facts. I'm definitely new to all of this so lets take it nice and easy ! To start I am taking user form data and validating with a php script that will hopefully be talking to a data base and storing form info.
So here are the forms guts:
<form method="post" action="test.php" name="contactform" id="contactform">
<div class="grid_6" id="register">
<center><h4>Required Information</h4></center>
<p>
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label for="email">Your Email:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label for="trew">Contact Phone:</label>
<input name="txtAreaCode" id="txtAreaCode" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPrefix" id="txtPrefix" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhone" id="txtPhone" style="width: 45px;" maxlength="4" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhoneExt" id="txtPhoneExt" style="width: 35px;" maxlength="10" value=""type="text">
ext.
</p>
<p>
<label for="zip">Zip Code:</label>
<input name="zip" id="zip" type="text" />
</p>
<p>
<label for="school">Name of School:</label>
<input name="school" id="school" type="text" />
</p>
<p>
<label for="title">Affiliation</label>
<select name="title">
<option selected="NULL">Please Select</option>
<option value="student">Student</option>
<option value="parent">Parent</option>
<option value="teacher">Teacher</option>
<option value="booster">Booster</option>
<option value="clubpres">Club President</option>
<option value="principal">Principal</option>
<option value="ptsa">PTSA</option>
</select>
</p>
</div>
<div class="grid_6" id="contactinfo">
<center><h4>Additional Information</h4></center>
<p>
<label for="color">School Colors:</label>
<input name="color" id="color" type="text" />
</p>
<p>
<label for="mascot">Mascot:</label>
<input name="mascot" id="mascot" type="text" />
</p>
<p>
<label for="tagline">Tagline/Motto:</label>
<input name="tagline" id="tagline" type="text" />
</p>
<p>
<label for="sbsize">Approximate Student Body Size:</label>
<input name="sbsize" id="sbsize" type="text" />
</p>
<p>
<label for="level">Interest Level:</label>
<select name="level">
<option value="1">Interested</option>
<option value="2">Slightly Interested</option>
<option value="3">Moderately Interested</option>
<option value="4">Highly Interested</option>
<option value="5">Extremely Interested</option>
</select>
</p>
<p>
<label for="verify">1 + 3 =</label>
<input name="verify" id="verify" class="small" type="text" />
</p>
<button class="fr" type="submit" id="submit">Send</button>
</form>
</div>
I take this form and make it all pretty with jquery now this is where I am getting the most headache of my life, I spent an hr rewriting from scratch thinking I had syntax errors or something. Come to find out this little gem was the problem, its all good we all make mistakes. Here is the jquery form file, this isn't my project i not even sure if this is needed but here is the source of my problems, Ive figured them all out but 1 (hopefully !).
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
.after('<img src="./img/form/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
txtAreaCode: $('#txtAreaCode').val(),
txtPrefix: $('#txtPrefix').val(),
txtPhone: $('#txtPhone').val(),
txtPhoneExt: $('#txtPhoneExt').val(),
zip: $('#zip').val(),
school: $('#school').val(),
title: singleValues = $("#title").val(),
color: $('#color').val(),
mascot: $('#mascot').val(),
tagline: $('#tagline').val(),
sbsize: $('#sbsize').val(),
level: $('#level').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#contactform #submit').attr('disabled','');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Alright now here is where I see the problem, im trying to get the values of the multiple choice to post to the last and final piece of code my php file that preforms the verification, Ive stripped down the fluff for debugging . But am sure that ive provided more than enough to fix. so here is the php...
<?php
if(trim($_POST['name']) == '') {
echo '<div class="error-message">Attention! You must enter your name.</div>';
exit();
} else {
$name = trim($_POST['name']);
}
if(trim($_POST['email']) == '') {
echo '<div class="error-message">Attention! You must enter your email.</div>';
exit();
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['txtAreaCode']) == '') {
echo '<div class="error-message">Attention! You must enter your txtAreaCode.</div>';
exit();
} else {
$txtAreaCode = trim($_POST['txtAreaCode']);
}
if(trim($_POST['txtPrefix']) == '') {
echo '<div class="error-message">Attention! You must enter your txtPrefix.</div>';
exit();
} else {
$txtPrefix = trim($_POST['txtPrefix']);
}
if(trim($_POST['txtPhone']) == '') {
echo '<div class="error-message">Attention! You must enter your txtPhone.</div>';
exit();
} else {
$txtPhone = trim($_POST['txtPhone']);
}
if(trim($_POST['zip']) == '') {
echo '<div class="error-message">Attention! You must enter your zip.</div>';
exit();
} else {
$zip = trim($_POST['zip']);
}
if(trim($_POST['school']) == '') {
echo '<div class="error-message">Attention! You must enter your school.</div>';
exit();
} else {
$school = trim($_POST['school']);
}
if(trim($_POST['title']) != 'NULL') {
echo '<div class="error-message">Attention! You must enter your title.</div>';
exit();
} else {
$title = trim($_POST['title']);
}
if(trim($_POST['verify']) == '') {
echo '<div class="error-message">Attention! Please enter the verification number.</div>';
exit();
} else if(trim($_POST['verify']) != '4') {
echo '<div class="error-message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
echo 'working';
?>
Now im sure there are many workarounds, I would like to know what I need to do to get this all working. I cant scrap jQuery as its a must for the project, Im sure it should be a simple fix. Fingers crossed as always forgive me for going overboard, i just feel I should let you guys see what my problem is. Ive noticed that if I dont use the 2nd piece of code at all it works wonders, but like i said I need to use it....
From what I gather im clearly doing something wrong in the .post action section as it isnt posting values of the dropdown.
I do a lot of these type forms for my company's application, and there's definitely some shortcuts you can take.
Serialize the data rather than using pure ID's. That way, you don't have to reference EVERY id to submit a form.
Use a validation script on the front end, it'll cut down on the back-end validation you have to worry about reporting back on after the submit. You can't get rid of back end validation, but using a front-end validation tool allows you to quickly and effectively warn the user of a potential problem without the "cost" of a submit. I really like the inline validator script.
If you post your data via an Ajax call rather than just a post, you can use the success callback to deal with issues like validation, success modal windows, etc.
When I do have to do a back-end validation alert, I ususally just make one common alert div at the top of the form and report back to that via the success element of the Ajax call (usually sending JSON) Remember, success on Ajax means the transaction happened, you can still have errors report back through from PHP and have to deal with an error case. By only doing one alert box, I save myself a ton of work and syntax, since most all errors get dealt with on the front end and the back-end is simply redundancy.
So, here's a sample of how I'd do a form on my site:
<div id="error" style="display:none"></div> <!-- error div, hidden -->
<form id="form">
<input type="text" id="name" name="name" class="validator"> <!-- don't forget names! -->
<input type="text" id="name" name="name2" class="validator">
<button id="submit">Send</button>
</form>
<script type="text/javascript">
$('#submit').click(function() { // onclick of submit, submit form via ajax
$.ajax({
url: "url_to_submit_to.php", //url to submit to
timeout: 30000,
type: "POST",
data: $('#form).serialize(), //gets form data, sends via post to processing page
dataType: 'json', //what to do with returned data, in this case, it's json
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(outstuff){
if (outstuff.success == 1) { //
alert('success')
} else {
$('#error').html('there is an error, do something');
//Do other stuff
}
}
});
});
</script>
Yes, you should add and id to the drop down menu, otherwise you can't call it as $("#title") in jquery
and in your jquery, it will try to submit when the page loads as you're calling it like
jQuery(document).ready(function(){
Try to change it to $(function(){
Hope it will work
It's weird isn't it, that you've nicely set IDs for all the other items in your form except for your drop downs, where you've only set names.
Forms submit the values of the controls using name, but you're referencing the value in your jquery code using id ('#').
So just try changing your dropdown declarations to have ids... like this:
<form method="post" action="test.php" name="contactform" id="contactform">
<div class="grid_6" id="register">
<center><h4>Required Information</h4></center>
<p>
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label for="email">Your Email:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label for="trew">Contact Phone:</label>
<input name="txtAreaCode" id="txtAreaCode" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPrefix" id="txtPrefix" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhone" id="txtPhone" style="width: 45px;" maxlength="4" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhoneExt" id="txtPhoneExt" style="width: 35px;" maxlength="10" value=""type="text">
ext.
</p>
<p>
<label for="zip">Zip Code:</label>
<input name="zip" id="zip" type="text" />
</p>
<p>
<label for="school">Name of School:</label>
<input name="school" id="school" type="text" />
</p>
<p>
<label for="title">Affiliation</label>
<select name="title" id="title">
<option selected="NULL">Please Select</option>
<option value="student">Student</option>
<option value="parent">Parent</option>
<option value="teacher">Teacher</option>
<option value="booster">Booster</option>
<option value="clubpres">Club President</option>
<option value="principal">Principal</option>
<option value="ptsa">PTSA</option>
</select>
</p>
</div>
<div class="grid_6" id="contactinfo">
<center><h4>Additional Information</h4></center>
<p>
<label for="color">School Colors:</label>
<input name="color" id="color" type="text" />
</p>
<p>
<label for="mascot">Mascot:</label>
<input name="mascot" id="mascot" type="text" />
</p>
<p>
<label for="tagline">Tagline/Motto:</label>
<input name="tagline" id="tagline" type="text" />
</p>
<p>
<label for="sbsize">Approximate Student Body Size:</label>
<input name="sbsize" id="sbsize" type="text" />
</p>
<p>
<label for="level">Interest Level:</label>
<select name="level" id="level">
<option value="1">Interested</option>
<option value="2">Slightly Interested</option>
<option value="3">Moderately Interested</option>
<option value="4">Highly Interested</option>
<option value="5">Extremely Interested</option>
</select>
</p>
<p>
<label for="verify">1 + 3 =</label>
<input name="verify" id="verify" class="small" type="text" />
</p>
<button class="fr" type="submit" id="submit">Send</button>
</form>
</div>