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.
Related
I have a form
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value="" /></div>
<p class='note' id='err[Name]'></p>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:
{
"err": {
"uname": "Please enter a user name"
}
"post": {
"uname": ""
}
}
or this is if the user did enter a name:
{
"post": {
"uname": "Bob Ross"
}
}
There could be multiple fields for post and err but it should still follow the same suite.
How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:
JSON.stringify($("#ajax-form").serializeArray())
A jsfiddle to full html:
https://jsfiddle.net/dzv8ttjn/1/
Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software
Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:
(note that I've changed your id's to be more sensible and updated the jQuery version used)
<?php
if(count($_POST)>0){
$response = ['err'=>[], 'post'=>[]];
foreach($_POST as $key => $value)
{
$response['post'][$key]=$value;
if(trim($value) == '') $response['err'][$key]='Please enter a '.$key;
}
echo json_encode($response);
exit;
}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$("#ajax-form").on('submit', function(event) {
event.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataString,
success: function(response) {
if (response) {
alert('test worked');
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="user-name" value="" />
<p class='note' id='name-error'></p>
</div>
<div>
<label for="password">Email Address <em>*</em></label>
<input id="password" type="text" name="email" value="" />
<p class='note' id='password-error'></p>
</div>
<div>
<label for="post[gender]">Gender <em>*</em></label>
<input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
<input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
<p class='note' id='gender-error'></p>
</div>
<div>
<label for="interests">Interests<em>*</em></label>
<input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
<input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
<input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
</body>
</html>
This question already has answers here:
How to get input field value using PHP
(7 answers)
Closed 8 years ago.
I am trying to register a new user by posting their form data to the database via a php scriptregister.php but I am getting an array of errors when I hit register, the data is supposed to be validated by a second script called validate.php. My register.php is shown below. Same errors exist when the form is empty and when is filled.
<?php require('scripts/validate.php');?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
<body>
<div id="mainWrapper">
<div id="register">
<?php if(isset($error)){echo "<div id='error'>".$error."</div>";}?>
<?php if(isset($success)){echo "<div id='success'>".$success."</div>";}?>
<form method="post" action="" >
<fieldset>
<legend>Register Here</legend>
<p>
<label for="Username">Username</label>
<input type="text" id="username"/>
</p>
<p>
<label for="Email">Email</label>
<input type="text" id="email"/>
<p>
<label for="Firstname">Firstname</label>
<input type="text" id="firstname"/>
</p>
<p>
<label for="Lastname">Lastname</label>
<input type="text" id="lastname"/>
</p>
<p>
<label for="Password">Password</label>
<input type="password" id="password"/>
</p>
<p>
<label for="Re-Type Password">Re-Type Password</label>
<input type="password" id="password2"/>
</p>
<p>
<label for="DOB">DOB</label>
<input type="text" id="dob">
</p>
<p>
<label for="Adress">Adress</label>
<input type="text" id="address"/>
</p>
<p>
<label for="Adress 2">Adress 2</label>
<input type="text" id="address2"/>
</p>
<p>
<label for="town">Town</label>
<input type="text" id="town"/>
</p>
<p>
<label for="county">County</label>
<input type="text" id="county"/>
</p>
<p>
<label for="Postalcode">PostalCode</label>
<input type="text" id="postcode"/>
</p>
<p>
<label for="contactno">Contact No.</label>
<input type="text" id="contact"/>
</p>
<input type="submit" name="submit" value="Register"/>
</fieldset>
</form>
</div>
</div>
</body>
</html>
And the validate.php is here
<?php include('connection.php');?>
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$email=$_POST['email'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$password=$_POST['password'];
$password2=$_POST['password2'];
$dob=$_POST['dob'];
$address=$_POST['address'];
$address2=$_POST['address2'];
$town=$_POST['town'];
$county=$_POST['county'];
$postcode=$_POST['postcode'];
$contact=$_POST['contact'];
$fetch=mysql_query("SELECT id FROM users WHERE email='$email'")or die(mysql_error());
$num_rows=mysql_num_rows($fetch);
if(empty($username)||empty($email) || empty($firstname) || empty($lastname) || empty($password) || empty($password2) || empty($dob) || empty($address) || empty($town)|| empty($postcode) || empty($contact))
{
$error= 'ALl * fields are required';
}
elseif (!filter_var($email,FILTER_VALIDATE_EMAIL))
{
$error= 'A valid email is required';
}
elseif (!empty($contact))
{
if (!is_numeric($contact))
{
$error= 'Enter a valid contact No.';
}
}
elseif ($password !=$password2)
{
$error= "Passwords don't match";
}
elseif ($num_rows >=1)
{
$error='We already have this email registered,try a new one!';
}
else
{
$password=md5($password);
$sql=mysql_query("INSERT INTO user(username,email,firstname,lastname,password,dob,address,address2,town,county,postcode,contact)VALUES('$username','$email','$firstname','$lastname','$password','$dob','$address','$address2','$town','$county','$postcode','$contact')");
if($sql)
{
header("location:login.php");
}
}
}
?>
I'll greatly appreciate guys.
Give your inputs a name property.
E.g:
<input type="text" id="username" name="username" />
The issue is that it's looking for name, but it doesn't exist.
This goes for all of your input fields, not just that specific one and not just for type="text".
When you POST data using a form, you need to specify the name of the data using the name attribute. Replace all of the id attributes with name and your form will work. For example:
<input type="text" id="username"/>
should become:
<input type="text" name="username"/>
Replace all elements' id with name. When form is submitted the element's information is submitted with associated name and not id.
e.g. <input type="text" id="username" name="username"/>
This isn't a PHP error, it's a HTML one.
POSTS variables are stated using the name tag in HTML, not the id tag.
Your inputs should look like this:
<input type="text" name="username"/>
Just change the id tags to name tags, and it should work.
Change your HTML Form
<?php require('scripts/validate.php');?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
<body>
<div id="mainWrapper">
<div id="register">
<?php if(isset($error)){echo "<div id='error'>".$error."</div>";}?>
<?php if(isset($success)){echo "<div id='success'>".$success."</div>";}?>
<form method="post" action="scripts/validate.php" >
<fieldset>
<legend>Register Here</legend>
<p>
<label for="Username">Username</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="Email">Email</label>
<input type="text" id="email" name="email"/>
<p>
<label for="Firstname">Firstname</label>
<input type="text" id="firstname" name="firstname"/>
</p>
<p>
<label for="Lastname">Lastname</label>
<input type="text" id="lastname" name="lastname"/>
</p>
<p>
<label for="Password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<p>
<label for="Re-Type Password">Re-Type Password</label>
<input type="password" id="password2" name="password2"/>
</p>
<p>
<label for="DOB">DOB</label>
<input type="text" id="dob" name="dob">
</p>
<p>
<label for="Adress">Adress</label>
<input type="text" id="address" name="address"/>
</p>
<p>
<label for="Adress 2">Adress 2</label>
<input type="text" id="address2" name="address2"/>
</p>
<p>
<label for="town">Town</label>
<input type="text" id="town" name="town"/>
</p>
<p>
<label for="county">County</label>
<input type="text" id="county" name="county"/>
</p>
<p>
<label for="Postalcode">PostalCode</label>
<input type="text" id="postcode" name="postcode"/>
</p>
<p>
<label for="contactno">Contact No.</label>
<input type="text" id="contact" name="contact"/>
</p>
<input type="submit" name="submit" value="Register"/>
</fieldset>
</form>
</div>
</div>
</body>
</html>
as others have stated here, your form elements need a name attribute. the id attribute is great for referencing the form elements in JavaScript or CSS. but with $_POST variables you need to specify the name. Hope this gives an understanding to why you need the name attribute instead of the id attribute.
I want to display contact address and permanent address same by clicking the checkbox.
For eg : if i type the contact address and click the checkbox then the same address should be displayed in permanent address field. How to do it using jquery?
Thanks in advance..
I have done it via java script. May be this is helpful for all.
Check box code:
<input type="checkbox" name="present" onclick="permanent(this.form)">
Java Script code:
<script language="JavaScript">
function permanent(p) {
if(p.present.checked == true) {
p.per_add.value = p.temp_address.value;
p.per_city.value = p.temp_city.value;
p.per_state.value = p.temp_state.value;
p.per_country.value = p.temp_country.value;
p.per_pin.value = p.temp_pin.value;
}
}
</script>
Contact Address
<input type="text" id="contact">
<input type="checkbox" id="check">
Contact Address <input type="text" id="permanent">
jquery is
$('#check').click(function() {
var c=$('#contact').val();
$("#permanent").val(c);
});
<script language="JavaScript">
$(document).ready(function(e) {
$('#check').click(function() {
var c=$('#contact').val();
$("#permanent").val(c);
});
});
</script>
</head>
<body>
<form>
<input type="text" id="contact">
<input type="checkbox" id="check">
Contact Address <input type="text" id="permanent">
</form>
function filladd()
{
if(filltoo.checked == true)
{
var tal11 =document.getElementById("tal").value;
var dist11 =document.getElementById("dist").value;
var pin11 =document.getElementById("pin").value;
var copytal =tal11 ;
var copydist =dist11 ;
var copypin =pin11 ;
document.getElementById("tal1").value = copytal;
document.getElementById("dist1").value = copydist;
document.getElementById("pin1").value = copypin;
}
else if(filltoo.checked == false)
{
document.getElementById("tal1").value='';
document.getElementById("dist1").value='';
document.getElementById("pin1").value='';
}
}
<label>Tal</label>
<br/>
<input type="Text" id="tal" name="Taluka1" class="" placeholder="" >
<br/>
<label>Distic</label>
<br/>
<input type="Text" id="dist" name="Distric1" placeholder="">
<br/>
<label>Pincodes</label>
<br/>
<input type="Text" id="pin" name="pincode1" placeholder="">
<br/>
<input type="checkbox" value="" name="filltoo" id="filltoo" onclick="filladd()" />Permanent Address same as Current Address <br/>
<label>Tal</label>
<br/>
<input type="Text" id="tal1" name="Taluka1" placeholder="" >
<br/>
<label>Distic</label>
<br/>
<input type="Text" id="dist1" name="Distric1" placeholder="">
<br/>
<label>Pincodes</label>
<br/>
<input type="Text" id="pin1" name="pincode1" placeholder="">
<br/>
For some reason my javascript won't execute when my submit button is pressed. It's supposed to leave an error message beside two textfields for a user's name and email address if they are empty, but it's not and I can't figure out why. Normally, when the two boxes are filled, the submit would go to a php page which sends an email. Any suggestions or help with fixing my javascript problem will be greatly appreciated.
This is my javascript:
//my javascript function
<script type='text/javascript'>
function validate_form()
{
$('span.error_message').html('');
var success = true;
$("#validate_form input").each(function()
{
if($(this).val()=="")
{
$(this).next().html("* You must complete this field"); // the error message
success = false;
}
});
return success;
}
</script>
and my form in html:
<form action=".....whatever....." method="POST" id="validate_form" onsubmit="return validate_form();">
<ol>
<li>
<span id="question">___ is your name? My name is Marie.</span>
<input type="text" name="q1" id="q1" />
</li>
<li>
<span id="question">___ are you from? I'm from Paris, France.</span>
<input type="text" name="q2" id="q2" />
</li>
<li>
<span id="question">Dave: ___ you like football</span>
<p>
<input type="radio" name="q6" value="1" id="q6_1" />
<label for="q6_1">Are</label>
<input type="radio" name="q6" value="2" id="q6_2" />
<label for="q6_2">Do</label>
<input type="radio" name="q6" value="3" id="q6_3" />
<label for="q6_3">Does</label>
<input type="radio" name="q6" value="4" id="q6_4" />
<label for="q6_4">Is</label>
</p>
</li>
<div id="username">
<p>
Before we begin, please enter your name and email:
<br />
<label for="user_name">Name: </label><input type="text" name="user_name" id="user_name" />
<span class="error_message" style="color:#FF0000"></span>
<br />
<label for="user_email">Email: </label><input type="text" name="user_email" id="user_email" />
<span class="error_message" style="color:#FF0000"></span>
</p>
</div>
<p style="width: 242px; margin: auto;">
<input type="submit" name="submit" value="Submit your answers" id="but" />
</p>
</form>
Edit: Fixed the problem with the javascript being called, but now the submit button isn't working even with the two textfields being filled.
$("#validate_form input") - I don't see validate_form anywhere; you need to add it or just use: $("input")
Firebug for firefox would help you debug these types of jscript issues. You can also use the Error Console in Firefox if you dont want to install firebug.
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>