Select at least one checkbox, PHP - php

I am trying to set up a form with validation. Setting up checkboxes that require the user to select at least one box is becoming quite a pain. I have tried most solutions that seemed promising from this and other forums, but to no avail.
So we have two different checkboxes that are going to different emails depending on which the user chooses. Right now, if you submit this form without selecting a checkbox, the form just refreshes, you get no error message. So I guess technically it's validating but the user is not getting the error message?
Code is a little messy, this is a test form we're setting up to experiment and see if we can make it functional before we build the real thing for a client.
Very novice with PHP and Javascript, by the way. Thanks in advance!
Here's the PHP code...
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
if(trim($_POST['checkbox']) == '') {
$agree = filter_input(INPUT_POST, 'checkbox');
$checked = '';
if( empty($agree) )
$errors['checkbox'] = true;
else{
$checked = 'checkbox';
}
}
//If there is no error, send the email
if(!isset($hasError) && $_POST['Charlotte']) {
$emailTo = 'Charlotte#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
//If there is no error, send the email
if(!isset($hasError) && $_POST['Mary']) {
$emailTo = 'Mary#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Here's the Javascript...
<script type="text/javascript">
$(document).ready(function(){
// validate signup form on keyup and submit
var validator = $("#contactform").validate({
rules: {
contactname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
checkbox: {
required: true,
},
subject: {
minlength: 2
},
message: {
minlength: 10
}
},
messages: {
contactname: {
required: "Please enter your name",
minlength: jQuery.format("Your name needs to be at least {0} characters")
},
email: {
required: "Please enter a valid email address",
minlength: "Please enter a valid email address"
},
checkbox: {
required: "Please select at least one location"
},
subject: {
minlength: jQuery.format("Enter at least {0} characters")
},
message: {
minlength: jQuery.format("Enter at least {0} characters")
}
},
// set this class to error-labels to indicate valid fields
success: function(label) {
label.addClass("checked");
}
});
});
</script>
Here's the form in HTML...
<div class="wrapper">
<div id="contactWrapper" role="form">
<h1 role="heading">Send a message</h1>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information and try again. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<div class="success">
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you for contacting us <strong><?php echo $name;?></strong>! Your email was successfully sent and we'll be in touch with you soon.</p>
</div>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div class="stage clear">
<label for="name"> Name:<em>*</em></label>
<input type="text" name="contactname" id="contactname" value="" class="required" role="input" aria-required="true" />
</div>
<div class="stage clear">
<label for="email">Email:<em>*</em></label>
<input type="text" name="email" id="email" value="" class="required email" role="input" aria-required="true" />
</div>
<div class="stage clear">
<ul>
<p>Please select a box*</p>
<li><input type='checkbox' name='Charlotte' value='1' id='checkbox' /><label for="Charlotte">Charlotte</label></li>
<li><input type='checkbox' name='Mary' value='2' id='checkbox' /><label for="Mary">Mary</label></li>
</ul>
</div>
<div class="stage clear">
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" value="" class="required" role="input" aria-required="true" />
</div>
<div class="stage clear">
<label for="message">Message:</label>
<textarea rows="8" name="message" id="message" class="required" role="textbox" aria-required="true"></textarea>
</div>
<p class="requiredNote"><em>*</em>Denotes a required field.</p>
<input type="submit" value="Send Message" name="submit" id="submitButton" title="Click here to submit your message!" />
</form>
</div>
</div>
</div>

if(trim($_POST['Charlotte']) != 1 and trim($_POST['Mary']) != 2){
$hasError = true;
}

<script language="javascript">
function Validate()
{
if (document.getElementById("check").checked == false )
{
alert("please select one checkbox");
return false;
}
}
</script>
<input type="checkbox" class="case" name="c[]" id="check">
<-----submit the code----->
<input name="one" onclick="Validate()" value="send" type="submit">

Related

Contact form on Yahoo Small Business Hosting

I am creating a site on Yahoo Small Business hosting, and am having issues with the PHP contact form that I use on my WordPress install on Bluehost. The form is:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = 'chris#bingetech.com';
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<div id="contact-wrap">
<?php if(isset($emailSent) && $emailSent == true)
{ ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occurred.<p>
<?php } } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="formList">
<li>
<label class="contact_labels" for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label class="contact_labels" for="email">Email: </label>
<input type="email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
</ul>
<div id="subContain">
<input type="submit" id="submit" value="Ask Away!"></input>
</div>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div>
I have the appropriate header calls and this does work on Bluehost, and from my research it appears Yahoo Small Business hosting can be tricky with contact forms/email. How can I get around this?
You should use some plugin instead of your own PHP code. Try Contact form 7 its completely customize-able

Html5 contact form - issues with javascript and php validation

Before I begin please except my appologises if this is to long, I'm totaly new to Html5 (usually design in Flash)and just getting started. I recently downloaded a free template called Brownie and understand most things but the contact form. It's using Javascript, PHP and Ajax I think. Ive got it kinda workin locally but things aren't working how I want. What I'm trying to do is make it validate fields with error message or success message e.t.c. this is the html form code I have:
<p class="required_info"><span>*</span> Required</p>
<!-- SUCCESS MESSAGE -->
<div class="success_box none"> Email successfully sent. Thank you! </div>
<!-- END SUCCESS MESSAGE -->
<!-- START CONTACT FORM -->
<form action="#" class="contact_form">
<p>
<label for="name">Name <span>*</span></label>
<input type="text" class="inputText" id="name" name="name" placeholder="Please enter your full name" pattern="[a-zA-Z ]+" onkeypress="return alpha(event,letters)" required minlength="5" maxlength="50" onpaste="return false;" tabindex="1"/>
<div class="success_title none"> You've entered your name. </div>
<div class="error_title none">* Please enter your full name. </div>
</p>
<div class="clear"></div>
<p>
<label for="company">Company </label>
<input type="text" class="inputText" id="company" name="company" placeholder="Company Name" minlength="3" maxlength="50" onpaste="return false;" tabindex="2"/>
</p>
<div class="clear"></div>
<p>
<label for="email">E-mail <span>*</span></label>
<input type="text" class="inputText" id="email" name="email" placeholder="Please enter a valid email address" required minlength="5" maxlength="50" onpaste="return false;" tabindex="3"/>
<div class="error_title none">* Please enter a valid email. </div>
</p>
<div class="clear"></div>
<p>
<label for="message">Message <span>*</span></label>
<textarea class="inputTextarea" cols="88" rows="6" id="message" name="message" placeholder="Please enter your message" required tabindex="4"></textarea>
<div class="error_title none">* Please enter your message. </div>
</p>
<div class="clear padding20"></div>
<p class="submit"><input type="reset" class="resetBtn button white" onclick="resetFields()" value="Reset" /> Send </p>
</form>
<!-- END CONTACT FORM -->
<!-- ERROR MESSAGE -->
<div class="error_box none"> Please complete all required fields [ highlighted in red ]. </div>
<!-- END ERROR MESSAGE -->
and this is the javascript code:
$(document).ready(function () {
$('#name').focus(function () {
$(this).removeClass('error_class');
});
$('#email').focus(function () {
$(this).removeClass('error_class');
});
$('#message').focus(function () {
$(this).removeClass('error_class');
});
$('.contact_form').submit(function () {
hasError = false;
if ($('#name').val() == '') {
$('#name').addClass('error_class');
hasError = true;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $('#email').val();
if (emailaddressVal == '') {
$('#email').addClass('error_class');
hasError = true;
}
else if (!emailReg.test(emailaddressVal)) {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#email').val() == '') {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#message').val() == '') {
$('#message').addClass('error_class');
hasError = true;
}
if (hasError == true) {
$('.info_box').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$.ajax({
type: 'POST',
url: 'contact.php',
cache: false,
data: $(".contact_form").serialize(),
success: function (data) {
if (data == "error") {
$('.success_box').hide();
$('.success_title').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$('.error_box').hide();
$('.error_title').hide();
$('.success_box').show();
$('.success_title').hide();
$('.resetBtn').hide();
$('.submit').hide();
}
}
});
}
return false;
});
});
This is the PHP code:
<?php
$your_email = 'name#domain.com'; // Your email address
$subject = 'Email from your contact form'; // Email subject
$name = isset($_POST['name']) && $_POST['name'] ? $_POST['name'] : ''; // Visitor Name
$company = isset($_POST['company']) && $_POST['company'] ? $_POST['company'] : ''; // Visitor Company
$email = isset($_POST['email']) && $_POST['email'] ? $_POST['email'] : ''; // Visitor Email
$message = isset($_POST['message']) && $_POST['message'] ? $_POST['message'] : ''; // Visitor Message
$website = isset($_POST['website']) && $_POST['website'] ? $_POST['website'] : ''; // Visitor Message
$full_message = 'Website: '.$website. "\r\n\r\n Message:".$message;
if($name && $email && $message)
{
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= 'Content-type: text/plain; charset=UTF-8' . "\r\n";
//------------------------------------------------
// Send out email to site admin
//------------------------------------------------
if(#mail($your_email, $subject, $full_message, $headers))
die("success");
else
die("error");
}
else
{
die("error");
}
?>
When the send button is pressed i want it to check if any data has been entered in each input field - if yes add success message if no add error message. I have the error message working but cant get the success message working on individual input fields. Any sugestions would be helpful...
I suspect it is because you are assigning true or false to each variable instead of the value of the variable in your php script. Isset($_POST[test]) is true, not the value of the test form value.

PHP, trying to add captcha to existing form

I am not a PHP programmer, but have used it a touch, enough to put in a contact form. However, I am trying to add a captcha field, which now works but the form does not validate it - so it submits no matter what
Can anybody help please? sorry if the code is messy and thanks in advance
code at the top of my page
<?php session_start() ?>
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
$hasError = true;
} else {
if($_SESSION["captcha"]==$_POST["captcha"]) {
}
}
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email address'; //Put your own email address here
$emailTo = 'email address'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .
$email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Code in the form:
[php]<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
[/php]
[edit ] 2011-12-20 8:22pm CST - updated the second block of code with the final code that the OP is using - based on off site chat.
There's a better way to write the code. I'm putting an example of this below. Ask questions and I'll update the code with comments explaining. I revamped the if statement you had for the captcha so that it didn't need a double if. Using || (or) in the if statement causes PHP to stop after testing the first condition (if the first condition evaluates to true). Therefore, if the variable is not set it never moves on to the comparison of POST with SESSION.
Also, I defaulted your hasError variable to false, and am testing for the boolean value. This is better because it makes sense. Think about the programmers who will come after you. If it makes sense, it'll be easier to work with. You might be that programmer :)
[edited to add session_start();]
<?php
session_start();
// default value
$hasError = false;
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if( ! isset( $_POST["captcha"] ) || $_SESSION["captcha"] != $_POST["captcha"] ) {
$hasError = true;
echo 'CAPTHCA is not valid; ignore submission<br>';
echo $_POST['captcha' . ' != ' . $_SESSION['captcha'] . '<br>';
}
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'email#email.com'; //Put your own email address here
$emailTo = 'email#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
// !!!!!!!!!!!!!!!! REMOVE \r\n from $emailTo or your form will be hacked !!!!!!!!!!!!!!!!!!!!!!
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
[edit - full code, edited and (hopefully) improved]
<?php
session_start();
function clean_for_email( $inbound )
{
return str_replace( array( "\n", "\r" ), "", $inbound );
}
// I really like the name of this function. :D
function outputInput( $name, $required )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'type="text"';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$attribs[] = 'value="' . htmlspecialchars( $_POST[$name] ) . '"';
}
echo '<input ' . implode( ' ', $attribs ) . '>';
}
//------------------------------------------------------------------------
function outputTextarea( $name, $required, $rows = 5 )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'rows="5"';
$value = '';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$value = htmlspecialchars( $_POST[$name] );
}
echo '<textarea ' . implode( ' ', $attribs ) . '>' . $value . '</textarea>';
}
// default value
$hasError = false;
$emailSent = false;
//If the form is submitted
if( count( $_POST ) && isset($_POST['submit'] ) ) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if ( ! preg_match( '/^.+#.+$/i', trim( $_POST['email'] ) ) ) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if ( ! array_key_exists( 'captcha', $_POST ) || $_SESSION['captcha'] != $_POST["captcha"] ) {
$hasError = true;
}
if( ! $hasError )
{
$captchaValid = true;
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'xxx'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.clean_for_email( $emailTo ).'>' . "\r\n" . 'Reply-To: ' . clean_for_email( $email );
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
}
?>
<? if( $hasError ) : ?>
<p class="error">Please check if you've filled all the fields with valid information Thank you.</p>
<? endif; ?>
<? if( $emailSent == true) : ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<? endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<? outputInput( 'name', true ); ?>
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<? outputInput( 'email', true ); ?>
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<? outputInput( 'subject', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<? outputTextarea( 'message', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<? outputInput( 'captcha', true ); ?>
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
if(isset($_POST["captcha"]))
You're missing a bracket.
Edited to show entire code.... Brackets added for captcha conditionals which were missing. As is, your code did not check if the captcha was set via post. It was only checking the session variable against the post variable. If both were blank, the form would mail. You may still have issues with captcha.php or the session variable.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
if($_SESSION["captcha"]==$_POST["captcha"])
{
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'enquiries#sjbprojects.com'; //Put your own email address here
$emailTo = 'sjbullen#gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: SJB Projects website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
else
{
echo 'CAPTHCA is not valid; ignore submission';
}
}
} else {
///message here if CAPTCHA is not set (via post)
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting SJB Projects. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>

PHP form takes back to top

I have PHP included a PHP form in my portfolio, that you can see here http://www.tinybigstudio.com The thing is that after SUBMIT, the page goes to TOP instead of staying at the bottom where the form is.
This is the PHP code I have:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#tinybigstudio.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' .$subject = "You have mail, yes!" . "\r\n" . 'Te lo manda: ' . $name;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
And this is the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<fieldset>
<label for="name">Name</label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required">
<label for="email">Email</label>
<input type="text" size="50" name="email" id="email" value="" class="required">
<label for="message">Message</label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
<input type="submit" value="S E N D" class="send" name="submit" onmouseover="this.className='send_hover';"
onmouseout="this.className='send';">
</form>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Message Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for sending a message!</p>
<?php }
?>
you need to add an anchor to the contact form and use this as the form action.eg:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>#contact" >
and add this 'pseudo-link' right before the contact form
<a name="contact">Contact me</a>
Now after submit user will be send to the form directly and not the top of the page
This is because you are submitting it to the same page that you are on, therefore the browser goes effectively refreshes with the $_POST data. If you want to stop this you need to use AJAX to submit it so that it happens in the background. Take a look at the API - http://api.jquery.com/jQuery.ajax/

Script should send an email containing form submission values, but no email is getting sent

So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.

Categories