PHP mail issues using javascript validation - php

I am trying to send an email from the same PHP page after Javascript validation but have some issues sending email. Can someone help me out with this?
Here is the JavaScript code:
<!-- -->
<script type="text/javascript">
function checkCheckBoxes() {
if (document.form.inforequired.checked == true)
{
if (document.form.option1.checked == false && document.form.option2.checked == false && document.form.option3.checked == false && document.form.option4.checked == false && document.form.option5.checked == false && document.form.option6.checked == false && document.form.option7.checked == false && document.form.option8.checked == false && document.form.option9.checked == false && document.form.option10.checked == false)
{
document.getElementById('error').innerHTML = "Please choose your options.";
return false;
}
if (document.form.option8.checked == true || document.form.option9.checked == true || document.form.option10.checked == true)
{
if (document.form.address.value == "" )
{
document.getElementById('erroraddress').innerHTML = "Please enter your address.";
return false;
}
}
else
{
document.forms["form"].submit();
return true;
}
}
else
{
document.forms["form"].submit();
return true;
}
}
</script>
<!-- Email -->
Here is the PHP code to send email in the else part.
<div id="content">
<h1 id="formSpacingHeading"> Visitor Information </h1>
<?if( !isset($_POST['submit'])):?>
<form id="form" name="form" onsubmit="return checkCheckBoxes();" action="" method="POST">
<p id="formSpacing"><label for="username" class="iconic user" > Name <span class="required">*</span></label> <input type="text" name="username" id="username" required="required" placeholder="Enter your name" /></p>
<p id="formSpacing"><label for="usermail" class="iconic mail-alt"> E-mail address <span class="required">*</span></label> <input type="email" name="usermail" id="usermail" placeholder="Enter your E-mail ID" required="required" /> </p>
<p id="formSpacing"><label for="contactno" class="iconic link"> Contact number <span class="required">*</span></label> <input type="text" pattern="^\d\d\d\d\d\d\d\d\d\d$" name="contact" id="contactno" placeholder="Enter your contact number" required="required" /></p>
<input type="submit" name="submit" value="Submit Form" />
</form>
<?php else :
$name=$_POST['username'];
$mail=$_POST['usermail'];
$contact=$_POST['contact'];
$to = "admin#xxx.com";
$subject = "New Visitor Information";
$message = $name;
$from = $mail;
$headers = "From:" . $from;
$email = mail($to, $subject, $message, $headers);
if($email){
echo "Thank you. We will keep you updated with the latest information.";
}
else{
echo "Error processing your request. Please try again later.";
}
?>
<? endif ?>

I'm not a PHP guru, but I have programmed a few basic things in it.
I think you have your if statement all wrong.
Change..
<?if( !isset($_POST['submit'])):?>
to
<?if( !isset($_POST['submit'])){?>
Change
<?php else :
To
<?php } else {
Change
?>
<? endif ?>
to
}?>

Related

When contact form button is clicked, site redirects to a custom post enrty

I've got this wordpress site with a custom post type, called reviews, loop and a contact form on a page. When I click on the submit button on the contact page, reguardless if the form contents matches the regex, it redirects the page to /reviewa/random name
I've removed the "reviews" part of the website and the form works.
What I would like to happen is to have the form send the email, without redirecting the site to /reviews/randomName
$(function() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('#contact-form').submit(function(e) {
$clientName = $("#contactName").val();
var valid = true;
// Remove any confirmation messages
$('p.confirmation').remove();
// Validate all fields that have a class of .required-field
$('.required-field').each(function() {
// Remove error class from all inputs and textareas and delete error messages before checking form again
$(this).removeClass('error').next('p').remove();
if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
$(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
valid = valid && false;
} else if ($(this).attr('id') === 'email') {
if (!$(this).val().trim().match(re)) {
$(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
valid = valid && false;
}
}
});
if (valid) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function(data) {
$('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
_gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
});
}
e.preventDefault();
});
});
<div id="reviews">
<h2>Our reviews</h2>
<div id="slider" class="flex-container">
<div class="flexslider">
<ul class="slides">
<?php $new = new WP_Query('post_type=reviews& posts_per_page=-1');
while ($new->have_posts()) : $new->the_post(); ?>
<li>
<?php echo the_post_thumbnail('portfolio-thumb');?>
<span class="review"> <?php the_content(); ?></span>
<span class="name"> <?php the_title(); ?></span>
</li>
<?php endwhile;?>
</ul>
</div>
</div>
</div>
<div id="contact">
<h2>To contact the instructor, plese enter your details below</h2>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){
//Check name
if(trim($_POST['contactName']) === '') {
$nameError = true;
$hasError = true;
}else{
$name = trim($_POST['contactName']);
}
//Check company name
if(trim($_POST['companyName']) === '') {
$companyNameError = true;
$companyNameError = true;
}else{
$companyName = trim($_POST['companyName']);
}
//Check address
if(trim($_POST['address']) === '') {
$addressError = true;
$addressError = true;
}else{
$address = trim($_POST['address']);
}
// Check email address exists and is valid
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
}else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
$emailError = 'You entered an invalid email address.';
$hasError = true;
}else{
$email = trim($_POST['email']);
}
if(trim($_POST['telNumber']) === '') {
$telError = true;
$hasError = true;
}else{
$telephone = trim($_POST['telNumber']);
}
//Check message
if(trim($_POST['message']) === ''){
$messageError = true;
$hasError = true;
}else{
$message = stripslashes(trim($_POST['message']));
}
//If there is no error, send the email
if(!isset($hasError)){
$emailTo = 'randomEmail#mail.com';
$subject = 'Contact from the Contact Us page';
$body = "Name: $name \n Email: $email \n Telephone: $telephone \n Poxtcode: $address . \n Message:\n$message";
$headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;
ssmtp($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if($emailSent == true) { ?>
<p class="confirmation">Thanks,
<?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
<ul>
<li>
<input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
<?php if($nameError) { ?>
<p class="error">Please enter your name.</p>
<?php } ?>
</li>
<li>
<input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
<?php if($addressError) { ?>
<p class="error">Please enter your postcode.</p>
<?php } ?>
</li>
<li>
<input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
<?php if($telError) { ?>
<p class="error">Please enter your mobile number.</p>
<?php } ?>
</li>
<li>
<input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
<?php if($emailError) { ?>
<p class="error">
<?php echo $emailError;?>
</p>
<?php } ?>
</li>
<li class="textarea">
<textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
<?php if($messageError) { ?>
<p class="error">Please enter a message.</p>
<?php } ?>
</li>
<li>
<input type="hidden" id="submitted" name="submitted" />
<button class="button" ">Send</button>
</li>
</ul>
</form>
</div>

Echo other content after form validation and submission

How to clear page content and show other content after I validate and submit a form?
<?php
if(isset($_POST['Confirm'])) {
$to = "email#email.com";
$error = 0;
$first_name = $_POST['first_name'];
//Validation things
if(trim($first_name) == '') {$error = 1; $first_namerr = 1;}
$msg ="
First Name:$first_name
-------------------------
";
$sub ="Contact";
$from = "From: Support form";
#mail($to, $sub, $msg, $from);
//How to clear actual content and echo other ?
}
}
?>
<form name="contact" id="contact" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
<label for="first_name" class="inner_text"><?php if ($error != 0){ if ($first_namerr == 1) {print("<font style='color: Red;'>");} }?>First Name<?php if ($error != 0){if ($first_namerr == 1) {print("</font>");}} ?></label>
<input id="first_name" name="first_name" size="30" type="text" value="<? echo $first_name; ?>" /><?php if ($error != 0){ if ($first_namerr == 1) {print('<img src="images/error.gif">');} }?>
<input type="submit" id="Confirm" name="Confirm" value="Confirm" />
</form>
I'm beginner in PHP, so please be explicit if you want to give an answer!
You could use an if/else statement to control the content being displayed - e.g:
<?php
if (isset($_POST['Confirm'])) {
// Your mail code
?>
Thank you, your message has been sent! <!-- This content is shown after form submission -->
<?php } else { ?>
<!-- Display your email form -->
<?php }; ?>

Strange letters in mail sent from mail-form in Wordpress

I need to change the charset of the mail form used on this side: http://www.erik-dalsgaard.dk/kontakt/
I need to include these letters: Æ, æ, Ø, ø, Å, å
Right now the letters it output when it sends a mail is Æ, Ø,à instead of the letters above.
The php for the mailform is:
<?php
/*
Template Name: Contact
*/
get_header(); ?>
<?php
//If the form is submitted
if(isset($_POST['submitted'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
$nameError = 'You forgot to enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['comments']) === '') {
$commentError = 'You forgot to enter your comments.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = get_option_tree('pr_contact_email');
$subject = 'Henvendelse fra hjemmeside fra '.$name;
$msubject = trim($_POST['subject']);
$body = "Navn: $name \n\nE-Mail: $email \n\nEmne: $msubject \n\nBesked: $comments";
$headers = 'From: Besked fra hjemmeside <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<div class="inner custom_content">
<div class="content <?php global_template(content); ?>">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php if(the_content()){ ?>
<div class="divider"></div>
<?php } ?>
<?php endwhile; endif; ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="form-success">
<?php echo get_option_tree('pr_form_success'); ?>
</div>
<?php } else { ?>
<div class="form-success">
<?php echo get_option_tree('pr_form_success'); ?>
</div>
<form action="<?php the_permalink(); ?>" id="contactForm" class="big_form" method="post" accept-charset="UTF-8">
<ul class="forms">
<li>
<label for="contactName">Navn: *</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField <?php if($nameError != '') { ?>hightlight<?php } ?>" />
</li>
<li><label for="email"><?php tr_translate(email); ?>: *</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email <?php if($emailError != '') { ?>hightlight<?php } ?>" />
</li>
<li><label for="subject">Emne:</label>
<input type="text" name="subject" id="subject" value="<?php if(isset($_POST['subject'])) echo $_POST['subject'];?>" />
</li>
<li class="textarea"><label for="commentsText">Besked: *</label>
<textarea name="comments" id="commentsText" rows="8" cols="60" class="requiredField <?php if($commentError != '') { ?>hightlight<?php } ?>"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
</li>
<li class="buttons">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit" class="button light"><?php tr_translate(submit_contact); ?></button>
<div class="loading"></div>
</li>
</ul>
</form>
</div><!-- .content End -->
<!-- Content End -->
<?php } ?>
<?php global_template(sidebar); ?>
<?php get_footer(); ?>
There are more places where this issue might come but fist verify if:1. MySQL 5 doesn't support full UTF-8 characters2. The e-mail client/host doesn't support full UTF-8 charactersIt is easy to verify this, check your website/your database if you detect this issues there also then you might try to use this plugin or search for similar ones.The bad part is that the issue might come from the e-mail client (ex: thunderbird or outlook) or even from the e-mail host.
I encontered an issue with some language specific characters that showed just fine in both yahoo and gmail webmail but not in any roundcube hosts. I ended up replaceing my characters with "normal" ones.(I haven't tryed the ubove plugin).Check the plugin it says it recodes the characters so it should do the trick.Regards.

Contact form issues

I'm having all kinds of issues with contact form. When I test on my home server everything runs smoothly. Once I upload it online it doesn't work. First there were problems with headers and now apparently "This web page has a redirect loop".
Here's my code. Please advice me what to do.
Thanks.
<?php
// Title: Contact Form - Dolce Forno GB
// Updated: 5/9/2012
//Validation code
if (!empty($_POST)) {
$errors = array();
//variables
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//All field are required
if (empty($name) === true || empty($email) === true || empty($phone) === true || empty($subject) === true || empty($message) === true ){
$errors[] = 'Please fill in all the fields.';
}
else {
//This regex allows only: a-z,A-Z, space, comma, full stop, apostrophe, dash
if (!preg_match("/^[a-zA-Z\s,.'-]+$/", $name)) {
$errors[] = 'Invalid name.';
/*die ("Invalid name."); */
}
//var_filter php function
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Invalid email address.';
}
//This regex allows only: 0-9, space, dash, brackets, min-max length: 10-15
if (!preg_match("/^[0-9\s]{10,15}$/", $phone)){
$errors[] = 'Invalid phone number.';
}
}
}
if (empty($errors)) {
//send email
mail('info#dolcefornogb.com', 'Contact Form', $subject, 'Message:' . $message,'From: ' . $name . $email . $phone);
header('Location:mail.php?sent');
exit ();
}
print_r($errors);
?>
<DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
else {
if (!empty($errors)){
echo '<ul>';
foreach ($errors as $error){
echo '<li>', $error,'</li>';
echo '</ul>';
}
}
?>
<form action="" method="post">
<p> <label for="name">Name
<span class="small">Add your name </span></label>
<input type="text" name="name" id="name"
<?php
if(isset($_POST['name']) === true){
echo 'value="', strip_tags($_POST['name']),'"';
}
?>
>
</p>
<p> <label for="email">E-mail address
<span class="small"> Add your e-mail</span></label>
<input type="text" name="email" id="email"
<?php
if(isset($_POST['email']) === true){
echo 'value="', strip_tags($_POST['email']),'"';
}
?>
>
</p>
<p><label for="phone">Phone<span class="small"> Add your phone number</span></label>
<input type="text" name="phone" id="phone"
<?php
if(isset($_POST['phone']) === true){
echo 'value="', ($_POST['phone']),'"';
}
?>
>
</p>
<p><label for="suject">Subject </label>
<input type="text" name="subject" id="subject"
<?php
if(isset($_POST['subject']) === true){
echo 'value="', strip_tags($_POST['subject']),'"';
}
?>
>
</p>
<p><label for="message">Message:</label>
<textarea name="message" id="messgae" rows="10" cols="50">
<?php
if(isset($_POST['message']) === true){
echo strip_tags($_POST['message']);
}
?></textarea>
</p>
<p><label for="call">Request Phone Call</label>
Yes:<input type="radio" value="Yes" name="call">
No:<input type="radio" value="No" name="call">
</p>
<p class="buttons">
<input type="submit" value="Send"> <input type="reset" value="Clear">
</p>
</form>
<?php
}
?>
Try redirecting to a different page with just the success message in it.
i.e. replace
header('Location:mail.php?sent');
with
header('Location:mail-success.php?sent');
Then get rid of (move to the new page)
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
Also try adding 303 status to the header call
http://www.electrictoolbox.com/php-303-redirect/

cant figure out php contact form verification woes

Hi I got a contact from script the internet that I have been messing around with, only problem is that the verification that I am trying to add to it just doesn't work. Basically in the form it has name, email, number, type and comment. My main verification woes are with the number field I would like it so that if it is empty it echos "no number" and when the person type in letters instead of numbers it will echo "you need to type with numbers". Something like lol. but I’m stuck. Can any of you geniuses help me? Thanks in advance here is the full code below. p.s. sorry about previous post i accidently cut off the script:$
<?php
$nowDay=date("d.m.Y");
$nowTime=date("H:i:s");
$subject = "E-mail from my site!";
if (isset($_POST['submit'])) {
//contactname
if (trim($_POST['name'] == '')) {
$hasError = true;
} else {
$name = htmlspecialchars(trim($_POST['name']));
}
//emailaddress
if (trim($_POST['email'] == '')) {
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i",trim($_POST['name']))) {
$hasError = true;
} else {
$email = htmlspecialchars(trim($_POST['email']));
}
//phonenumber
if (trim($_POST['number'] == ''))
{
$fake_num = true;
}
else if(!is_numeric($_POST['phonenumber']))
{
$fake_num = true;
}
else
{
$number = htmlspecialchars(trim($_POST['number']));
}
//type
$type = trim($_POST['type']);
//comment
if (trim($_POST['comment'] == '')) {
$hasError = true;
} else {
$comment = htmlspecialchars(trim($_POST['comment']));
}
if (!isset($hasError) && !isset($fake_num)) {
$emailTo = 'email#hotmail.com';
$body = " Name: $name\n\n
Email: $email\n\n
Phone number: $number\n\n
Type: $type\n\n
Comment: $comment\n\n
\n This message was sent on: $nowDay at $nowTime";
$headers = 'From: My Site <'.$emailTo.'>'."\r\n" .'Reply-To: '. $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php
if(isset($hasError))
{
echo"<p>form has error</p>";
}
?>
<?php
if(isset($fake_num))
{
echo"<p>wrong num</p>";
}
?>
<?php
if(isset($emailSent) && $emailSent == true)
{
echo "<p><strong>Email Successfully Sent!</strong></p>";
echo "<p>Thank you <strong> $name </strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>";
}
?>
<div id="stylized" class="myform">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="bookingform" id="bookingform">
<h1>Booking form</h1>
<label>
Name
<span class="small"></span>
</label>
<input type="text" name="name" id="name" class="required"/>
<label>
Your email:
<span class="small"></span>
</label>
<input type="text" name="email" id="email" class="required"/>
<label>
Contact Number:
<span class="small"></span>
</label>
<input type="text" name="number" id="number" class="required" />
<label>
Car required:
<span class="small"></span>
</label>
<select name="type" id="type">
<option selected="selected">Manual</option>
<option>Automatic</option>
</select>
<label>
Comment:
<span class="small"></span>
</label>
<textarea cols="" rows="" name="comment" id="comment" class="required"></textarea>
<button type="submit" name="submit">Submit</button>
</form>
</div>
For checking whether a number has been entered you can use:
if (!preg_match('/^?[0-9]{0,10}$/', $_POST['number'])) {
echo "Please enter a valid number"; //Failed to meet criteria
}
Here you can also specify the amount of numbers that would constitute your valid number with the braces {0,10}, in this case, the number can be up to 11 digits long. If you required it to be only 11 digits long, then use {11}.
If you wish to check if a number has been entered at all you can use:
if (empty($_POST['number'])) {
echo "Please enter a valid number"; //Field was left empty
}
PHP does have a built-in email validation function that you can use
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
which returns true if the entered email is in the correct format.

Categories