I've a HTML 5 form with mandatory fields etc. The submit button when clicked checks for mandatory fields before submitting. While I've changed the behavior to open a link in another window, I can't make the form check the mandatory fields and send the links after this is done.
I need the form to also check if the fields have been filled and then process with validation and external link but rather not have the link opened while the user skip from filling it.
My form's codes read as follows:
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<form method="post" action="process.php">
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
<span id="loading"></span>
<input type="submit" value="Submit" id="submit-button" Link" onClick="window.open ('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G6ZNL8H4JXBB8', 'newwindow')"/>
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script src="js/script.js"></script>
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script> DD_belatedPNG.fix('img, .png_bg');</script>
<![endif]-->
And my Process.php file is as follows
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//validate form data
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
//send email if all is ok
if($formok){
$headers = "From: myemail#mail.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Telephone: </strong> {$telephone} </p>
<p><strong>Enquiry: </strong> {$enquiry} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
mail("myemail#mail.com","New Enquiry",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'name' => $name,
'email' => $email,
'telephone' => $telephone,
'enquiry' => $enquiry,
'message' => $message
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
You can do all in single php file . (say form_disp_process.php)
<?php
if( isset($_POST) )
{
// check validation set formok=true or false
if($formok)
{
//mail data
// if u want to redirect user to new welcome page after mailing
echo "
<script language='JavaScript'>
window.location = 'welcomepage.php';
//window.open ('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G6ZNL8H4JXBB8', 'newwindow')"
</script>
";
}
}
else
{
//init variables
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<form method="post" action="form_disp_process.php">
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
span id="loading"></span>
<input type="submit" value="Submit" id="submit-button" Link" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
</div>
<?php
} //else close
?>
Since you mentioned HTML5 .I am adding another answer
Use Javascript to validate your form and then redirect to paypal site
Mistakes you made :
You have used attribute "required" for mandatory fields but have you have to give value .
Like this required="required"
Reference : http://www.w3schools.com/html5/att_textarea_required.asp
There is no attribute called data-minlength for textarea
Reference : http://www.w3schools.com/html5/tag_textarea.asp
Code HTML5 + JavaScript :
<head>
<script type="text/javascript">
function checklength()
{
var x=document.forms["myform"]["message"].value;
if(x.length < 20)
{
alert("Your message must be greater than 20 charcter");
document.getElementById('errors').innerHTML = 'Your message must be greater than 20 charcter';
return false;
}
return true;
}
</script>
</head>
<body>
<div id= "errors"> </div>
<form method="post" name="myform" onsubmit="return checklength();" action="mail_me_and_redirect_to_paypal.php" >
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" required="required" value="sdfdf" placeholder="John Doe" autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" required="required" value="dsfds#sdf.com" placeholder="johndoe#example.com" />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" required="required" value="werwe" />
<label for="enquiry">Enquiry: </label>
<select id="enquiry" name="enquiry">
<option value="Choose" selected>Choose</option>
<option value="Purchase">Purchase</option>
<option value="Distribution">Distribution</option>
<option value="Inquire">Inquire</option>
</select>
<label for="message">Message: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required="required" ></textarea>
<input type="submit" value="Submit" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
</body>
Related
Just starting playing with recaptcha and need to send form data to another file for further processing (sending to CRM). Before the captcha was implemented the form had the property action='post-sign-up', which was sending the data without problem to the post-sign-up.php.
But now with recaptcha I understand the form action property needs to be empty, and I can't figure out a way of sending the data to the other file after verifying that captcha.
When completing the form (pressing submit) the captcha is triggered. If verification fails it would show the error, but if it succeeds I need the form data to be submitted and sent to another file which does some further processing.
In other words:
user completes the form
user press submit
captcha verification occurs
if captcha is not ok, error will be shown (redirect to the same page)
if captcha is ok, the form data should be submitted to another file for further processing
(post-sign-up.php)
if post-sign-up is ok, it will show the thank you page (post-sign-up-success.php)
Thank you!
This is only client-side (no server)
sign-up.php
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/libs/jquery.cookie.js"></script>
<script type="text/javascript" src="/js/libs/jquery.deparam.js"></script>
<script type="text/javascript" src="/js/libs/jquery.urlparam.js"></script>
<script type="text/javascript" src="/js/libs/jquery.fancybox.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/libs/jquery.fancybox-media.js?v=1.0.6"></script>
<?php
define("RECAPTCHA_V3_SECRET_KEY", "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z");
if(isset($_POST['token']))
{
if (isset($_POST['email']) && $_POST['email']) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$firstName = filter_var($_POST['firstName'], FILTER_SANITIZE_STRING);
} else {
// set error message and redirect back to form...
header('location: sign-up.php');
exit;
}
$token = $_POST['token'];
$action = $_POST['action'];
// call curl to POST captcha request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => RECAPTCHA_V3_SECRET_KEY, 'response' => $token)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$arrResponse = json_decode($response, true);
// verify the response
if($arrResponse["success"] == '1' && $arrResponse["action"] == $action && $arrResponse["score"] >= 0.7) {
// valid submission
$captchaError = false;
// Maybe here I can send all the form data to another file which does some further processing
} else {
// spam submission
$captchaError = true;
}
}
?>
<section class="lc-layout-component border bank-font">
<div class="lc-content component-padding gutters">
<section class="cc-column-component regular-grid">
<?php if (isset($this) && $this->wasError()) { ?>
<div class="error">
<p><?php echo $this->getErrorMessage(); ?></p>
</div>
<?php
}?>
<!--old action: /post-sign-up -->
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="company">Company</label>
<input id="company" value="Pepe Ltd" type="text" class="one-full bank-color-grey bank-input" name="company" placeholder="Company" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getCompany() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="phone">Phone</label>
<input id="phone" value="+4565464565" type="text" class="one-full bank-color-grey bank-input" name="phone" placeholder="Phone" autocomplete="off" data-validate="true" data-type="phone" value="<?php isset($this) ? print $this->getPhone() : print ''; ?>">
<br/>
<label class="label bank-color bank-label" for="referredBy">Referred by </label>
<input id="referredBy" value="Pepa" type="text" class="one-full bank-color-grey bank-input" name="referredBy" placeholder="Referred By" autocomplete="off" value="<?php isset($this) ? print $this->getCashManager() : print ''; ?>">
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
<?php
isset($arrResponse["score"]) && $captchaError == true && print 'error. Please try again later ';
print ' score: ';
print $arrResponse["score"];
?>
</div>
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
</form>
</section>
</div>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
var email = $('#email').val();
console.log(email);
var firstName = $("#firstName").val();
console.log(firstName);
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
$('#bank-form').unbind('submit').submit();
});;
});
});
</script>
Update:
I've added echo $errors to the end of my code. Now I am getting that all fields are required although all are filled:
} else {
echo $errors;
}
I've created a simple php e-mail form with this example (link). And jQuery form validator (link).
Now what I get after submiting a form is just a empty "contact-form-handler.php" page.
You can see the form live at: mantasmilka.com/#contactPage
What could be the problem? Below is my code.
contact-form-handler.php
<?php
$errors = '';
$myemail = 'mantas#mantasmilka.com';//<-----Put Your email address here.
if(empty($_POST['infoname']) ||
empty($_POST['infocompany']) ||
empty($_POST['infoemail']) ||
empty($_POST['infophone']) ||
empty($_POST['infodescription'])
)
{
$errors .= "\n Error: all fields are required";
}
$jobtype = $_POST['jobtype'];
$budget = $_POST['budget'];
$location = $_POST['location'];
$infoname = $_POST['infoname'];
$infocompany = $_POST['infocompany'];
$infoemail = $_POST['infoemail'];
$infophone = $_POST['infophone'];
if (isset($_POST['infodescription'])) {
$infodescription = $_POST['infodescription'];
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$infoemail))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Jobtype: $jobtype \n Budget: $budget \n Location: $location \n Name: $infoname \n Company: $infocompany \n E-mail: $infoemail \n Phone: $infophone \n ".
"Message \n $infodescription";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $infoemail";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
// header('Location: http://www.mantasmilka.com/index.php');
header('Location: index.php');
exit();
} else {
echo $errors;
}
?>
my form in index.php:
<form id="contactform" method="post" name="contact_form" action="contact-form-handler.php">
<div class="left">
<fieldset class="jobtype">
<legend>Job type</legend>
<input type="radio" name="jobtype" id="project" value="project" required>
<label for="project">Project</label>
<input type="radio" name="jobtype" id="part-time" value="part-time" >
<label for="part-time">Part-time</label>
<input type="radio" name="jobtype" id="full-time" value="full-time" >
<label for="full-time">Full-time</label>
</fieldset>
<fieldset class="budget">
<legend>Budget</legend>
<input type="radio" name="budget" id="budget5k" value="budget5k" required>
<label for="budget5k">5k € ></label>
<input type="radio" name="budget" id="budget10k" value="budget10k" >
<label for="budget10k">5k - 10k €</label>
<input type="radio" name="budget" id="budget15k" value="budget15k" >
<label for="budget15k">15k € <</label>
</fieldset>
<fieldset class="location">
<legend>Location</legend>
<input type="radio" name="location" id="locremote" value="locremote" required>
<label for="locremote">Remote</label>
<input type="radio" name="location" id="loclocal" value="loclocal" >
<label for="loclocal">Local with relocation</label>
</fieldset>
</div>
<div class="right">
<fieldset class="contactinfo">
<legend>Your Contact Info</legend>
<div class="input-holder">
<input type="text" name="infoname" id="infoname" value="" required data-validation="alphanumeric">
<label for="infoname">Name</label>
</div>
<div class="input-holder">
<input type="text" name="infocompany" id="infocompany" value="" required data-validation="alphanumeric">
<label for="infocompany">Company</label>
</div>
<div class="input-holder">
<input type="text" name="infoemail" id="infoemail" value="" required data-validation="email">
<label for="infoemail">E-mail</label>
</div>
<div class="input-holder">
<input type="text" name="infophone" id="infophone" value="" required data-validation="number">
<label for="infophone">Phone</label>
</div>
<div class="input-holder textarea">
<textarea name="infodescription" form="contact_form" rows="4" required></textarea>
<label for="infodescription">Message</label>
</div>
<div class="input-holder submit">
<input type="submit" name="submit" value="Submit" required/>
</div>
</fieldset>
</div>
</form>
text field should look like this don't put form tag in here
<textarea name="infodescription" rows="4" required></textarea>
in php make the if statement like this the first ( opens the if statement the last ) closes it and take not of how i used the other brackets
if(
(empty($_POST['infoname'])) ||
(empty($_POST['infocompany'])) ||
(empty($_POST['infoemail'])) ||
(empty($_POST['infophone'])) ||
(empty($_POST['infodescription']))
)
{
$errors .= "\n Error: all fields are required";
}
The efficient way to solve the problem is:
$('#contactform').submit(function(ev) {
ev.preventDefault();
if($('#infodescription').val() == '')
{
alert('Description is required');
return false;
}
//add other validation
this.submit(); // If all the validations succeeded
});
By this you can avoid the unwanted server load.
I bought a WP theme a few months ago and it works great! I am trying to edit the contact.php / sendmail.php
I have successfully added in a field, it shows up in the body of the email and sends correctly. However, I am have a lot of trouble getting the new field "school(s) of interest" to highlight properly (with hidden text) when the field hasn't been filled. The contact form in question can be found here: http://www.northbrookmontessori.org/school-tours/
sendmail.php
<?php
//validate fields
$errors = '';
//has the form's submit button been pressed?
if( !empty( $_POST['myformsubmit'] ) )
{
// HAS THE SPAM TRAP FIELD BEEN FILLED IN?
if( !empty( $_POST['favouriteColour'] ) )
{
exit;
}
$myemail = $_POST['youremail'];
$thankyou = $_POST['thankyou'];
$formerror = $_POST['formerror'];
if(empty($_POST['name']) ||
empty($_POST['school']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$school = $_POST['school'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email_address)) { $errors .= "\n Error: Invalid email address"; } //send email
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission from $name";
$email_body = "$name has sent you this email through the contact form: \n \n".
"Name: $name \n".
"School(s) of interest: $school \n".
"Email: $email_address \nMessage: \n\n$message";
$headers = "From: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: ' . $thankyou);
}
else {
header('Location: ' . $formerror);
}
}
?>
contact.php
<!-- ***** CONTACT -->
<div class="block_wrapper <?php if($bb_animation == 'yes'){ echo 'animation' . $anim1_number; ?> animated <?php } ?><?php echo ' '.$custom_width; ?>">
<div class="box_full<?php if($margin_top != ''){echo ' ' . $margin_top;} ?><?php if($margin_bottom != ''){echo ' ' . $margin_bottom;} ?><?php if($custom_classes != NULL){echo ' ' . $custom_classes;} ?>">
<form id="theform" class="form mt35" method="post" action="<?php echo get_template_directory_uri(); ?>/sendmail.php">
<p class="hRow">
<label for="favouriteColour">Favourite colour (do not fill in)</label>
<span><input type="text" name="favouriteColour" id="favouriteColour" value="" /></span>
</p>
<input type="hidden" name="youremail" id="youremail" value="<?php if(!empty($contact_email)){echo $contact_email;} ?>" />
<input type="hidden" name="thankyou" id="thankyou" value="<?php if(!empty($contact_thankyou)){echo $contact_thankyou;} ?>" />
<input type="hidden" name="formerror" id="formerror" value="<?php if(!empty($contact_error)){echo $contact_error;} ?>" />
<p class="name validated">
<label for="name">Name</label>
<span><input type="text" name="name" id="name" /></span>
</p>
<p class="school validated">
<label for="school">School(s) of interest</label>
<span><input type="text" name="school" id="school" /></span>
</p>
<p class="email validated">
<label for="email">E-mail</label>
<span><input type="text" name="email" id="email" /></span>
</p>
<p class="text validated">
<label for="message">Message</label>
<textarea name="message" id="message" rows="50" cols="100"></textarea>
</p>
<p class="submit">
<input type="submit" class="buttonmedium float_r" name="myformsubmit" value="Send Email" />
</p>
<p id="error">* There were errors on the form, please re-check the fields.</p>
</form>
</div>
<div class="clear"></div>
</div><!-- ***** END CONTACT -->
you need to go to the file:
http://www.northbrookmontessori.org/wp-content/themes/modular/js/settings.js?ver=4.2.2
and edit the top where it says:
// Place ID's of all required fields here.
add in school
I went off an tutorial when creating this form, and have edited and formatted it to match my site. The original form works just the way I want it to, and mine works except for instead of sliding up on submitting the form, the page refreshes. I have compared the code so many times and looked all over the place and can't figure out what I changed or left out that is causing mine to refresh the page. Any help would be greatly appreciated. I've spent hours working on this, and I'm sure it's somethings small.
Here is the original tutorial: http://www.hongkiat.com/blog/ajax-html5-css3-contact-form-tutorial/
Here is my code:
PHP in the header:
<?php
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = '<strong>WARNING:</strong> Please provide your full name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = '<strong>WARNING:</strong> Please provide an email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'Please provide a valid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// require a phone from user
if(trim($_POST['phone']) === '') {
$phoneError = '<strong>WARNING:</strong> Please provide a phone number.';
$hasError = true;
} else {
$phone = trim($_POST['phone']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = '<strong>WARNING:</strong> Please provide a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$emailTo = 'myemail#gmail.com';
$subject = 'Submitted message from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nComments: $comments";
$headers = 'From: ' .' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>
Form with PHP:
<div class="separator">
<h5>Keep in touch</h5>
<div class="sep_line"></div><!-- separator line -->
</div>
<div class="clear"></div>
<div class="twoThirds">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="Note Success hideit">
<p><strong>SUCCESS: </strong>Your message has been sent.</p>
</div>
<?php } else { ?>
<div id="respon">
<?php if(isset($hasError) || isset($captchaError) ) { ?>
<div class="Note Failure hideit">
<p><strong>FAILURE: </strong>Error submitting the message.</p>
</div>
<?php } ?>
<form action="contact.php" method="post" id="contact-form">
<label for="name">
Name: * </label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" size="22" tabindex="1" class="nameInput">
<?php if($nameError != '') { ?>
<br><div class="Note Warning hideit"><p><?php echo $nameError;?></p></div>
<?php } ?>
<label for="email">
Email: * </label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" size="22" tabindex="2" class="emailInput">
<?php if($emailError != '') { ?>
<br><div class="Note Warning hideit"><p><?php echo $emailError;?></p></div>
<?php } ?>
<label for="phone">
Phone: * </label>
<input type="text" name="phone" id="phone" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>" size="22" tabindex="3" class="webInput">
<?php if($phoneError != '') { ?>
<br><div class="Note Warning hideit"><p><?php echo $phoneError;?></p></div>
<?php } ?>
<label for="message">
Your Message: * </label>
<textarea name="comments" id="commentsText" tabindex="4" class="messageInput"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<br><div class="Note Warning hideit"><p><?php echo $commentError;?></p></div>
<?php } ?>
<br>
<input name="reset" class="button" type="reset" id="reset" tabindex="5" value="Reset">
<input name="submit" class="button" type="submit" id="submit" tabindex="6" value="Submit">
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div>
<?php } ?>
</div><!-- end main contact-us -->
Javascript:
<script type="text/javascript">
<!--//--><![CDATA[//><!--
$(document).ready(function() {
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="Note Warning hideit">Your forgot to enter your '+labelText+'.</span>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="Note Warning hideit">Sorry! You\'ve entered an invalid '+labelText+'.</span>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p class="Note Success hideit"><strong>SUCCESS: </strong>Your message has been sent.</p>');
});
});
}
return false;
});
});
//-->!]]>
</script>
The solution is simple,
Mainly you are missing to specify the correct id of the form that you are submitting,
<form action="contact.php" method="post" id="contact-form">
Where it should be
<form action="contact.php" method="post" id="contact-us">
The there are some missing attributes in the form, which you are selecting in javascript
Eg.
.requiredField
.error
Try to correct those also.
EDIT
Roughly edited form block
<form action="contact.php" method="post" id="contact-us">
<label for="name">
Name: * </label>
<input type="text" name="contactName" id="contactName" value="<?php if (isset($_POST['contactName'])) echo $_POST['contactName']; ?>" size="22" tabindex="1" class="nameInput requiredField">
<?php if ($nameError != '') { ?>
<br><div class="error"><p><?php echo $nameError; ?></p></div>
<?php } ?>
<label for="email">
Email: * </label>
<input type="text" name="email" id="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" size="22" tabindex="2" class="email requiredField">
<?php if ($emailError != '') { ?>
<br><div class="error"><p><?php echo $emailError; ?></p></div>
<?php } ?>
<label for="phone">
Phone: * </label>
<input type="text" name="phone" id="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>" size="22" tabindex="3" class="webInput requiredField">
<?php if ($phoneError != '') { ?>
<br><div class="error"><p><?php echo $phoneError; ?></p></div>
<?php } ?>
<label for="message">
Your Message: * </label>
<textarea name="comments" id="commentsText" tabindex="4" class="messageInput requiredField"><?php if (isset($_POST['comments'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['comments']);
} else {
echo $_POST['comments'];
}
} ?></textarea>
<?php if ($commentError != '') { ?>
<br><div class="error"><p><?php echo $commentError; ?></p></div>
<?php } ?>
<br>
<input name="reset" class="button" type="reset" id="reset" tabindex="5" value="Reset">
<input name="submit" class="button" type="submit" id="submit" tabindex="6" value="Submit">
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
YET ANOTHER EDIT
In your JS file change,
$(this).parent().append('<span class="Note Warning hideit">
to
$(this).parent().append('<span class="error">
and
$(this).before('<p class="Note Success hideit">
to
$(this).before('<p class="tick">
as in the tutorial.
I need to check that the check box is checked (required) and need the validation to perform much like the other form fields, and then i need to post the value in email.
PHP for entire form as it stands:
<?php
if(isset($_POST['formtrigger'])):
//config
define('FORM_SENDTO','hello#domain.com');
define('FORM_SUBJECTLINE','Enquiry from website');
define('ERR_MSG_FIELD_REQUIRED','This field is required.');
define('ERR_MSG_FIELD_INVALIDEMAIL','Please enter a valid email address.');
//setup validation rules
//Name
$validation_rules['forename']['required'] = true;
$validation_rules['surname']['required'] = true;
//Company
$validation_rules['company']['required'] = true;
//Address
$validation_rules['address']['required'] = true;
//Tel
$validation_rules['tel']['required'] = true;
//Email
$validation_rules['email']['required'] = true;
$validation_rules['email']['valid_email'] = true;
//Enquiry
$validation_rules['enquiry']['required'] = true;
//title/gender
$validation_rules['ts1']['required'] = true;
$validation_rules['ts2']['required'] = true;
//validate the form
$formerrors=0;
foreach($_POST as $formfield_name=>$formfield_value):
//set the entered value as a sanitised string
$_POST_SANITISED[$formfield_name] = filter_var($formfield_value,FILTER_SANITIZE_STRING);
//Check if required
if($validation_rules[$formfield_name]['required']):
if(!strlen($formfield_value)>0):
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_REQUIRED;
endif;
endif;
//Check if valid email required
if($validation_rules[$formfield_name]['valid_email']):
if(!filter_var($formfield_value,FILTER_VALIDATE_EMAIL)):
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_INVALIDEMAIL;
endif;
endif;
endforeach;
//process form and send message if validation passed
if($formerrors==0):
$email_msg[] = "New general enquiry\n\n-----------\n";
$email_msg[] = "Title: ".$_POST_SANITISED['ts1']."\n";
$email_msg[] = "Gender: ".$_POST_SANITISED['ts2']."\n";
$email_msg[] = "Forename: ".$_POST_SANITISED['forename']."\n";
$email_msg[] = "Surname: ".$_POST_SANITISED['surname']."\n";
$email_msg[] = "Company: ".$_POST_SANITISED['company']."\n";
$email_msg[] = "Address: ".$_POST_SANITISED['address']."\n";
$email_msg[] = "Telephone No.: ".$_POST_SANITISED['tel']."\n";
$email_msg[] = "Email: ".$_POST_SANITISED['email']."\n";
$email_msg[] = "Enquiry: ".$_POST_SANITISED['enquiry']."\n";
$email_msg[] = "-----------\n";
$email_msg = implode('',$email_msg);
$email_headers = 'From: ' . $_POST_SANITISED['email'] . "\r\n" .
'Reply-To: ' . $_POST_SANITISED['email'] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail(FORM_SENDTO,FORM_SUBJECTLINE,$email_msg,$email_headers);
header('Location: ?msgsent=1#thanks');
endif;
endif;
function errorOutput($fieldname=''){
global $fielderrors;
if(count($fielderrors[$fieldname])>0):
foreach($fielderrors[$fieldname] as $err_msg):
$error_str .= '<div class="form-fielderror-msg">'.$err_msg.'</div>';
endforeach;
endif;
return $error_str ? $error_str : false;
}
function errorClass($fieldname=''){
global $fielderrors;
$error_class = '';
if(count($fielderrors[$fieldname])>0):
$error_class = 'form-fielderror';
endif;
return $error_class ? $error_class : false;
}
?>
Here is the HTML:
<?php if($_GET['msgsent']==1): ?>
<h1>Thanks for your enquiry. If requested, we will get in touch shortly.</h1>
<?php else: ?>
<div id="form-cont">
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<div class="form-element">
<label for="ts1">Title:*</label>
<select name="ts1" class="<?=errorClass('ts1')?>">
<option value="">-- Please select --</option>
<option value="Mr" <?=$_POST['ts1']=='Mr' ? 'selected="selected"' : '' ?>>Mr</option>
<option value="Mrs" <?=$_POST['ts1']=='Mrs' ? 'selected="selected"' : '' ?>>Mrs</option>
<option value="Miss" <?=$_POST['ts1']=='Miss' ? 'selected="selected"' : '' ?>>Miss</option>
<option value="Ms" <?=$_POST['ts1']=='Ms' ? 'selected="selected"' : '' ?>>Ms</option>
</select>
<?=errorOutput('ts1')?>
</div>
<div class="form-element">
<label for="ts2">Gender:*</label>
<select name="ts2" class="<?=errorClass('ts2')?>">
<option value="">-- Please select --</option>
<option value="Male" <?=$_POST['ts2']=='Male' ? 'selected="selected"' : '' ?>>Male</option>
<option value="Female" <?=$_POST['ts2']=='Female' ? 'selected="selected"' : '' ?>>Female</option>
</select>
<?=errorOutput('ts2')?>
</div>
<div class="form-element">
<label for="forename">Forename:*</label>
<input type="text" name="forename" class="textbox <?=errorClass('forename')?>" value="<?=$_POST['forename']?>" />
<?=errorOutput('forename')?>
</div>
<div class="form-element">
<label for="surname">Surname:*</label>
<input type="text" name="surname" class="textbox <?=errorClass('surname')?>" value="<?=$_POST['surname']?>" />
<?=errorOutput('surname')?>
</div>
<div class="form-element">
<label for="company">Company:*</label>
<input type="text" name="company" class="textbox <?=errorClass('company')?>" value="<?=$_POST['company']?>" />
<?=errorOutput('company')?>
</div>
<div class="form-element">
<label for="address">Address:*</label>
<input type="text" name="address" class="textbox <?=errorClass('address')?>" value="<?=$_POST['address']?>" />
<?=errorOutput('address')?>
</div>
<div class="form-element">
<label for="tel">Telephone No:*</label>
<input type="text" name="tel" class="textbox <?=errorClass('tel')?>" value="<?=$_POST['tel']?>" />
<?=errorOutput('tel')?>
</div>
<div class="form-element">
<label for="email">Email:*</label>
<input type="text" name="email" class="textbox <?=errorClass('email')?>" value="<?=$_POST['email']?>" />
<?=errorOutput('email')?>
</div>
<div class="form-element">
<label for="enquiry">Your Enquiry:*</label>
<textarea name="enquiry" class="<?=errorClass('enquiry')?>"><?=$_POST['enquiry']?></textarea>
<?=errorOutput('enquiry')?>
</div>
<div class="form-element">
<label for="terms">Terms and Conditions</label>
<input type="checkbox" name="terms" class="checkbox <?=errorClass('terms')?>" value="<?=$_POST['terms']=1?>" />
<?=errorOutput('terms')?>
</div>
<div class="form-element">
<p class="clear">* denotes required field.</p>
<input type="submit" class="submit" name="submit" value="Send" alt="Submit" title="Submit" />
</div>
<input type="hidden" name="formtrigger" value="1" />
</form>
</div>
<?php endif ?>
The checkbox in question as at the bottom:
<div class="form-element">
<label for="terms">Terms and Conditions</label>
<input type="checkbox" name="terms" class="checkbox <?=errorClass('terms')?>" value="<?=$_POST['terms']=1?>" />
<?=errorOutput('terms')?>
</div>
Many thanks for you help! :)
if (isset($_POST['terms']))
{
// checked
}
There is no way in the world this code would run validations of check box is the least of your problem
A. You have so many Notice: Undefined index errors like 55
B. This would not work expect your server supports short tags ''
C. Too Many duplication
I would only correct the error of validation you requested but trust me so many things are wrong
$formerrors=0;
$_POST_SANITISED = array();
foreach($_POST as $formfield_name=>$formfield_value){
//set the entered value as a sanitised string
$_POST_SANITISED[$formfield_name] = filter_var($formfield_value,FILTER_SANITIZE_STRING);
//Check if required
if(isset($validation_rules[$formfield_name]['required']))
{
if(!strlen($formfield_value)>0){
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_REQUIRED;
}
}
//Check if valid email required
if(isset($validation_rules[$formfield_name]['valid_email']))
{
if(!filter_var($formfield_value,FILTER_VALIDATE_EMAIL)){
$formerrors++;
$fielderrors[$formfield_name][] = ERR_MSG_FIELD_INVALIDEMAIL;
}
}
};
if(!isset($_POST['terms']))
{
$formerrors++;
$fielderrors["terms"][] = ERR_MSG_FIELD_REQUIRED;
}