Disable form submit unless checkbox is ticked - php

I need to tweak the code for a basic form. I'm not a PHP developer, I'm a graphic designer and I have just basic knowledge of PHP. What I need to do is to disallow this form from sending unless the checkbox is ticked. I found some code on the web, that I think should do the trick, but it needs some changes and I'm not sure which part of code to tweak. I looked into the PHP and I'm aware that there is a good bunch of code that I don't need, I see there is also a JavaScript, I already changed the form layout in HTML and left just what's needed.
Here is how the form looks:
<!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>Untitled Document</title>
</head>
<body>
<?php
session_start();
if(isset($_POST['Submit'])) {
$youremail = 'somemail#mail.com';
$fromsubject = 'Request from form';
$bedrijfsnaam = $_POST['bedrijfsnaam'];
$naam = $_POST['naam'];
$mail = $_POST['mail'];
$adres = $_POST['adres'];
$plaatsnaam = $_POST['plaatsnaam'];
$postcode = $_POST['postcode'];
$branche = $_POST['branche'];
$telefoon = $_POST['telefoon'];
$message = $_POST['message'];
$to = $youremail;
$mailsubject = 'Bericht ontvangen van'.$fromsubject.' Actie Pagina';
$body = $fromsubject.'
Bedrijfsnaam: '.$bedrijfsnaam.'
Naam Contact Persoon: '.$naam.'
E-mail: '.$mail.'
Adres: '.$adres.'
Plaatsnaam: '.$plaatsnaam.'
Postcode: '.$postcode.'
Branche: '.$branche.'
Telefoonnummer: '.$telefoon.'
vraag of Wens: '.$message.'
|---------End Message----------|';
echo "thank you for your request we will contact you asap.";
mail($to, $subject, $body);
}
else
{
echo "Error Please <a href='terms.php'>try again</a>";
}
/* if (isset($_POST['Submit'])) {
$to = 'somemail#mail.com';
$subject = 'Bericht ontvangen van'.$fromsubject.' Actie Pagina';
$body = '';
unset($_POST['Submit']);
foreach($_POST as $key => $val) {
$body .= ucfirst($key).": ".$val."\n";
}
if (mail($to, $subject, $body)) {
echo "Mail sent to ".$to." successfully.";
} else {
echo "Mail could not be sent.";
}
}*/
?>
</body>
</html>
And here is the HTML and Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>PHP form check box example</title>
<script type = "text/javascript">
//email form validation
function everif(str) {
var at = "#"
var punct = "."
var lat = str.indexOf(at)
var lstr = str.length
var lpunct = str.indexOf(punct)
if (str.indexOf(at) == -1)
{
alert("Valid email must be entered")
return false
}
if (str.indexOf(at) == -1 ||
str.indexOf(at) == 0 ||
str.indexOf(at) == lstr) {
alert("Valid email must be entered")
return false
}
if (str.indexOf(punct) == -1 ||
str.indexOf(punct) == 0 ||
str.indexOf(punct) == lstr) {
alert("Valid email must be entered")
return false
}
if (str.indexOf(at,(lat+1)) != -1) {
alert("Valid email must be entered")
return false
}
if (str.substring(lat-1,lat) == punct ||
str.substring(lat+1,lat+2) == punct) {
alert("Valid email must be entered")
return false
}
if (str.indexOf(punct,(lat+2)) == -1) {
alert("Valid email must be entered")
return false
}
if (str.indexOf(" ") != -1) {
alert("Valid email must be entered")
return false
}
return true
}
function evalid() {
var emailID = document.contact_form.mail
if (everif(emailID.value) == false) {
emailID.focus()
return false
}
//empty field validation
var naam = document.contact_form.naam
if ((naam.value == null) || (naam.value == "")) {
alert("Fields marqued with * must be entered")
naam.focus()
return false
}
var telefoon = document.contact_form.telefoon
if ((telefoon.value == null) || (telefoon.value == "")) {
alert("Fields marqued with * must be entered")
telefoon.focus()
return false
}
var branche = document.contact_form.branche
if ((branche.value == null) || (branche.value == "")) {
alert("Fields marqued with * must be entered")
branche.focus()
return false
}
return true
}
</script>
<style type = "text/css">
#content {
width:100%;
text-align:center;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
#button {
width:100%;
}
</style>
</head>
<body>
<div id = "content">
Some terms of trade goes here<br>
Some terms of trade goes here<br>
Some terms of trade goes here<br>
Some terms of trade goes here<br>
Some terms of trade goes here<br>
Some terms of trade goes here<br>
Some terms of trade goes here
</div>
<div id = "button">
<form name = "contact_form" method = "post"
id = "contactform" action = "form2.php" onSubmit = "return evalid()">
I accept the above terms of trade
<input type = "checkbox" name = "emailmarketing"
id = "emailmarketing" value = "emailmarketing" />
<input type = "submit" name = "Submit" value = "Submit">
</form>
</div>
</body>
</html>
Thanks in advance for any help!

Edit this section of PHP:
vraag of Wens:
'.$message.'
|---------End Message----------|';
$check = $_POST['emailmarketing'];
if ($check==false)
{
echo "Error Please <a href='terms.php'>try again</a>";
}
else
{
echo "thank you for your request we will contact you asap.";
mail($to, $subject, $body);
}
?>
Or if you want to validate via javascript:
Add this to the evalid function:
var checkBox=document.contact_form.emailmarketing
if (checkBox.value==false){
alert("Please accept the terms");
checkBox.focus()
return false
}

You must check if the chekbox checked.
Change
<?php
session_start();
if(isset($_POST['Submit'])) {
...
to
<?php
if(!isset($_SESSION))session_start();
if(isset($_POST['Submit']) && $_POST['emailmarketing'] == 'emailmarketing') {
...

You will have to add one more condition into javascript function evalid that is
if document.getElementById('emailmarketing').value==false {
alert("you must accept terms of trade");
return false;
}
While submitting the form it will check for that checkbox is checked or not.

You can stop the user for submitting the form (if unchecked) by using jquery
if($('#your_checkbox_id').attr('checked')) {
return true;
}else{
return false;
}

Related

Undefined variables in PHP after sending data via Ajax

I am trying to send data via Ajax to my php file and process it, I don't know where is the error Ajax seems to be Okay but after receiving data via $_POST in php file but when I am trying to echo my variables I am getting errors.
I am sending data using a POST;
here is my frontend code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- <form id="ArticleEnterForm" method="POST" action="ProcessFormData.php"> -->
<div id="warningsDiv">
wowowo
</div>
<label id="ArticleTitleLabel">Article title: </label>
<input id="ArticleTitleInputField" type="text" name="">
<div>
</div>
<iframe id="ArticleiFrame"></iframe>
<label>Enter article: </label>
<textarea id="ArticleContentTextArea"></textarea>
<label id="ArticleFileNameLabel">Enter file name(save as):</label>
<input id="ArticleFileNameInputField" type="text">
<button id="SubmitButton" name="submitButton">Submit</button>
<!-- </form> -->
<script>
function SubmitForm() {
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
//submitting using POST method
var sendDataRequest = new XMLHttpRequest();
sendDataRequest.open("POST", "ProcessFormData.php", true);
sendDataRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendDataRequest.onreadystatechange = function () {
if (sendDataRequest.readyState === 2) {
warningsDiv.innerHTML = "<strong>Loading...</strong>";
}
if (sendDataRequest.readyState === 4 && sendDataRequest.status === 200) {
console.log("dtatus: " + sendDataRequest.readyState);
warningsDiv.innerHTML = sendDataRequest.responseText;
}
}
var dataToSend = "ArticleTitleData=" + articleTitle + "&ArticleContentData=" + articleContent + "&ArticleFileNameData=" + articleFileName;
sendDataRequest.send(dataToSend);
}
var submitButton = document.getElementById('SubmitButton');
submitButton.addEventListener("click", SubmitForm);
</script>
</body>
</html>
and here is my PHP code:
<?php
ini_set('display_errors', 'On'); //to get errors displayed
$ArticleTitle = "";
$ArticleContent = "";
$ArticleFileName = "";
if(isset($_POST['ArticleTitleData'])){
$ArticleTitle = $_POST['ArticleTitleData'];
}else {
echo("no var artn ");
}
echo("data was entered successfully following data was entered: Title: " . $ArticleTitle );
?>
where is the error in this script.
the response text I am seeing on browser screen is:
data was entered successfully following data was entered: Title: undefined
The problem is that some of the variables you are using, are undefined in the scope you are trying to use them in:
function CheckFields() {
// The variables defined with `var` exist in the scope of this function
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
// No `ArticleTitle`, etc. here...
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
Note that you are defining your variables using var in the CheckFields() function. So the scope of these variables is that function and anything in it, they will not be available outside of the CheckFields() function.
To solve that, you can return them from or define them before the function.
For example:
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
// etc.
Note that if you need the warningsDiv outside of the function as well, you would need to treat it the same.
Yes, I figured out what was the problem
short answer:
when I was not calling the CheckFields(); properly
long answer:
Instead of if(CheckFields() == true){ //something } I was doing if(CheckFields == true){ //something }
I came to know this because when I was submitting the input field empty there was no change in warningsDiv as it was supposed to be when CheckFields(); function is called.
Thanks everyone for helping me...

How to validate users input before action

I'm really new in internet languages and i try to figure out how it's possible to validate the users input before method call but i just can't make it work yet.
<html>
<head>
</head>
<body>
<?php
$grade = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$returned = test_input($_POST["grade"]);
if(!$returned) ?
}
function test_input($data)
{
if ( !is_numeric($data) || $data>100 || $data<0 )
{
$data = "";
echo 'The input should be a number between 0 and 100 ';
echo "<br>";
echo 'Try again';
return false;
}
return true;
}
?>
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade">
</form>
</body>
</html>
Further to my and other comments, your function has incorrect if clauses, specifically your greater than, less than. I would suggest not echoing any strings from it otherwise you have a limited-use function.
function input_valid($data = false)
{
if(empty($data))
return false;
elseif($data && !is_numeric($data))
return false;
else
return (($data <= 100) && ($data > 0));
}
if(isset($_POST["grade"])) {
if(input_valid($_POST["grade"])) {
// Do stuff.
}
else {
echo 'Invalid input. Must be a number between 1 and 100.';
}
}
NOTE: I feel it's important to re-iterate my comment above which is you SHOULD NOT rely solely on client-side validation. The user can turn it off, then you have no validation. Client-side validation should be considered only as a "user experience" feature, not a "security" feature.
You can try using jquery
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade" class="grade" onkeyup="">
</form>
<script type='text/javascript' src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
$(function(){
$('input.grade').bind("keyup change", function(){
validateGrade( $(this).val() );
});
});
function validateGrade(g){
if(g>100 || g<0){
alert('The input should be a number between 0 and 100');
}
}
</script>

Contact form with Jquery and PHP

Attempting to set up a Jquery and PHP Contact form on my website found here http://www.greenlite.co.uk/Contactus.html
I think I'm doing something wrong with the PHP file. I've put the necessary email into the PHP file but I'm not sure if I've linked it in the main code correctly, or even how to do that. Or even where to add it on the root file.
Here's the code I'm using;
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Form</title>
<link href="js/style.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/contact/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/contact/jquery.form.js"></script>
<script type="text/javascript" src="js/contact.js"></script>
</head>
<body>
<div id="wrap">
<h1>Contact Greenlite Controls</h1>
<form id="contactform" action="processForm.php" method="post">
<table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" id="email" name="email" /></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" rows="5" cols="20"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Send" id="send" /></td>
</tr>
</table>
</form>
<div id="response"></div>
</div>
</body>
</html>
And here is the PHP
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "You must enter a name.";
} else {
$errors[] = "Name must be at least 2 characters.";
}
}
if(!$email) {
$errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
$errors[] = "You must enter a valid email.";
}
if(strlen($message) < 10) {
if(!$message) {
$errors[] = "You must enter a message.";
} else {
$errors[] = "Message must be at least 10 characters.";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul> </span>");
}
// Send the email
$to = "mick#greenlite.co.uk";
$subject = "Contact Form: $name";
$message = "$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
Basically if it's not clear, after I use the contact form I get "Sending" but it does not die. I don't get a Success message and the mail doesn't send. I can only assume it's something to do with the PHP.
I've put the PHP file into a folder on the root called php and tried to call it from "action="php/ProcessForm.php" but this didn't make a difference.
Why do you do not validate the form with Jquery, instead inside the PHP??
Try to use AJAX to send your form and Jquery UI to response your user with the sucess or failure.
Try to use the .serialize() (http://api.jquery.com/serialize/) function in query and $.ajax.
This way, you'll can clean up your php file and find the error.
Look a simple example of the code:
Call the submit funcion:
$().ready(function(e) {
$("#cad_cliente").submit(function(e){
e.preventDefault();
insertDataForm(getDataForm());
});
return false;
});
Serialize the parameters:
function getDataForm(){
var params=$("#cad_cliente").serialize();
return params;
}
Post the values in your php file:
$.ajax({
type: 'post',
url:'registra.php',
data:params,
cache:false,
success: function(){
Alert("mesenge");
}
});
}
Glad if i could help you...

Mail not sending after valiidation

this is an expanded version of a question I asked last night, but with much more detail. All my php files and js file are in a folder called js one level down from my html pages.
I have a contact form that mails the content of my shopping cart and form inputs to my email using php mail. I am validating the form on submit:
<form name="theForm" id="theForm" onsubmit="return validateFormOnSubmit(this)">
with this submit button:
<input type=submit name=Submit value=Send style=cursor:pointer/>
The validation works as it should, here is the code (validate.js):
function setSelRange(inputEl, selStart, selEnd) {
if (inputEl.setSelectionRange) {
inputEl.focus();
inputEl.setSelectionRange(selStart, selEnd);
} else if (inputEl.createtextRange) {
var range = inputEl.createtextRange();
range.collapse(true);
range.moveEnd('character', selEnd);
range.moveStart('character', selStart);
range.select();
}
}
window.onload=function(){
setSelRange(document.theForm.textbox, 0, 0);
}
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateName(theForm.name);
reason += validatePhone(theForm.phone);
reason += validateEmail(theForm.emaile);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
simpleCart.checkout()
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = '#3399ff';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateName(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = '#3399ff';
error = "Please enter a name.\n";
} else if ((fld.value.length < 2) || (fld.value.length > 30)) {
fld.style.background = '#3399ff';
error = "The nme is too long!\n";
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value); // valu
trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = '#3399ff';
error = "Please enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = '#3399ff';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = '#3399ff';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
error = "Please enter a phone number.\n";
fld.style.background = '#3399ff';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number can only contain numbers.\n";
fld.style.background = '#3399ff';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. area code.\n";
fld.style.background = '#3399ff';
}
return error;
}
I am tring to then run the function simpleCart.checkout() when the form successfully validates: (from the above code)
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
simpleCart.checkout()
}
here is the function from simpleCart.js I am tring to call, (set to emailCheckout):
me.checkout = function() {
if( me.quantity === 0 ){
error("Cart is empty");
return;
}
switch( me.checkoutTo ){
case PayPal:
me.paypalCheckout();
break;
case GoogleCheckout:
me.googleCheckout();
break;
case Email:
me.emailCheckout();
break;
default:
me.customCheckout();
break;
}
};
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "js/sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("wsp_key", wsp_key));
form.appendChild(me.createHiddenElement("wsp_code", wsp_code));
form.appendChild(me.createHiddenElement("textbox", textbox));
form.appendChild(me.createHiddenElement("name",name));
form.appendChild(me.createHiddenElement("phone",phone));
form.appendChild(me.createHiddenElement("emaile",emaile));
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
It recieves the cart info, inputs and captcha key and code from the form and actions sendjs.php to mail it to me:
(from the code above)
form.action = "js/sendjs.php";
If the captcha code is correct it will mail it to me and redirect to "from-accepted.php" page, if not it will redirect to a "form-rejected.php" page (sendjs.php):
<?php
include_once("wsp_captcha.php");
if(WSP_CheckImageCode() != "OK") {
header('location:/form-rejected.php');
die();
}
$to = 'diysoakwells#hotmail.com';
$subject = 'Order Inquiry';
$jcitems = " <p><b>ORDER:</b></p><p> " . $_POST['jcitems']."<p/>" . "<p><b>Total:</b> $" . $_POST['jctotal']."</p>";
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= 'From: inquiry#diysoakwells.com' . "\r\n" .
'Reply-To: noreply#diysoakwells.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$name = $_POST['name'];
$phone = $_POST['phone'];
$emaile = $_POST['emaile'];
$textbox = $_POST['textbox'];
$text = "<html><body><p>This form was submitted on Your Web Site on \n $date at\n $time</p><p><b>Message:</b>\n$textbox</p><p><b>Customers Email Address:</b>$emaile</p><p><b>Customers Name:</b> $name </p><p><b>Customers Phone Number:</b> $phone </p></html></body>";
$body = $text . $jcitems;
mail($to, $subject, $body, $headers);
Header('Location: ../form-accepted.php');
?>
The problem is that after validation is doesn't action sendjs.php and just reloads the contact page. Debugger is showing no error and I have tested simpleCart.checkout by other means and it should work. Sorry for the length of this post but I am stumped and am losing business (and a lot of sleep trying to get it to work) not having this form functioning.
here is a link to the page:
http://www.diysoakwells.com.au/cart.php
Does anyone have any suggestions? I have to pop out now for an hour but I will be monitoring this post and when I return, working on the problem for at least the next four or five hours or until its fixed. Thanks in advance.
Jamie
In Chrome I got this error: Uncaught TypeError: Cannot read property 'textbox' of undefined on validate.js:16
and BTW I got redirected to http://www.diysoakwells.com.au/form-rejected.php, so the post was ok it seems. Previously it didn't work because my cart was empty

I can't get my form to validate AND submit using jQuery validation

I have been digging around on here and other sites for a while and am stuck. I'm trying to use jQuery to validate my form (concurrently as the user fills out the form) and, if the form is valid have it submit to a php page I have created to process the contents of the form. I have been able to have it validate but I can't have it also submit it...if I put a value in for the form action parm then it bypasses the validation. Please help...
I apologize, in advance, for the bad coding.
Here is my jquery-validate.js:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage())
return true;
else
return false;
});
My form code is pasted here:
<form method="post" id="customForm" action="rcv-form1.php">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
And here is my php that receives the form (this is just for testing now. i will email or insert into mySQL once i know i can properly validate stuff):
<html><head>
<title>Display form values</title>
</head>
<body>
<?
//$valid_form = TRUE;
//$bad_field_count = 0;
$table1_beg = '<center><table align="center" bordercolor="#F00" width="600px" border="3" cellspacing="1" cellpadding="1"><caption>Form status</caption><tr><th scope="col">Field Name</th><th scope="col">Field Value</th></tr>';
$row_beg = '<tr><td>';
$td = '</td><td>';
$row_end = '</td></tr>';
$table1_end = '</table></center>';
function checkEmail($field)
{
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
//echo "This ($field) email address is considered valid.";
return $field;
} else {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//global $bad_field_count; $bad_field_count++;
return $field;
}
}
function SanitizeString($field)
{
$field = filter_var($field, FILTER_SANITIZE_STRING);
//if(is_null($field) || $field == '') { global $bad_field_count; $bad_field_count++;}
return $field;
}
// ensure form data is valid
$name=SanitizeString($_POST['name']);
//$email=$_POST['email'];
$email = checkEmail($_POST['email']);
$pass1=SanitizeString($_POST['pass1']);
$pass2=SanitizeString($_POST['pass2']);
$message=SanitizeString($_POST['message']);
echo $table1_beg;
echo $row_beg . "Name" . $td . "<u>" . $name . "</u>" . $row_end;
echo $row_beg . "Email" . $td . "<u>" . $email . "</u>" . $row_end;
echo $row_beg . "Password 1" . $td . "<u>" . $pass1 . "</u>" . $row_end;
echo $row_beg . "Password 2" . $td . "<u>" . $pass2 . "</u>" . $row_end;
echo $row_beg . "Message" . $td . "<u>" . nl2br($message) . "</u>" . $row_end;
//echo $row_beg . "Number of bad fields" . $td . "<b>" . $bad_field_count . "</b>" . $row_end;
echo $table1_end;
//}
?>
</body></html>
Problem 1: When I have form action="" I can validate the form only after hitting submit...it doesn't say it's invalid until after submitting when I thought it should do it concurrently as it is typed in.
Problem 2: If I have my form action set to anything but "" it will ignore the jQuery validation all together.
I'm new to the form validation stuff. Can someone point me in the right direction? Thanks, in advance!
You have a few problems, your form submit code doesn't have curly brackets around it, and you don't have a function for validate email, try this:
//global vars
var form = $("#customForm");
var fname = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName() {
//if it's NOT valid
if (fname.val().length < 4) {
fname.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
fname.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
function validatePass2() {
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if (pass1.val() != pass2.val()) {
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else {
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}
function validatePass1() {
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if (pass1.val().length < 5) {
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else {
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
return true;
}
}
function validateEmail(){
//add validation for email here
return true;
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
fname.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
fname.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function() {
if (validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage()) {
return true;
}
else {
return false;
}
});
I've gave you an easy way to validate your all inputs/textarea within one function but you have to complete it, I've just gave you the structure and only name validation has done as an example for you and I hope you can understand it easily. If you need more help/difficulties just leave a message. This should be placed inside ready event.
var info={
'nameInfo':$("#nameInfo"),
'emailInfo':$("#emailInfo"),
'pass1Info':$("#pass1Info"),
'pass2Info':$("#pass2Info")
}
$('#customForm input,textarea').not("#send").bind('blur keyup', function(e)
{
e.stopPropagation();
var el=$(e.target);
var id=el.attr('id');
if(el.attr('id')=='message' && e.type=="keyup")
{
return false;
}
else
{
if(id=="name")
{ if(el.val().length < 4)
{
el.addClass("error");
info.nameInfo.text("We want names with more than 3 letters!");
info.nameInfo.addClass("error");
return false;
}
else
{
el.removeClass("error");
info.nameInfo.text("What's your name ?");
info.nameInfo.removeClass("error");
return true;
}
}
if(id=="email")
{
// Your email validation code
}
if(id=="pass1")
{
// Your pass1 validation code
}
if(id=="pass2")
{
// Your pass2 validation code
}
if(id=="message")
{
// Your message validation code
}
}
});

Categories