Getting Selected Dropdown content to show in a form-generated email - php

I have a small contact form:
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<legend>Please fill in the following form to contact us</legend>
<label for="name"><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for="company"><span class="required">*</span> Company</label>
<input name="company" type="text" id="name" size="30" value="" />
<br />
<label for="email"><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for="phone"><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="" />
<br />
<label for="purpose"><span class="required">*</span> Purpose</label>
<select id="purpose" style="width: 300px; height:35px;">
<option value="I am interested in your services">I am interested in your services!</option>
<option value="I am interested in a partnership">I am interested in a partnership!</option>
<option value="I am interested in a job">I am interested in a job!</option>
</select>
<br />
<label for=comments><span class="required">*</span> Comments</label>
<textarea name="comments" cols="40" rows="3" id="comments" style="width: 350px;"></textarea>
<p><span class="required">*</span> Please help us control spam.</p>
<label for=verify accesskey=V> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />
<input type="submit" class="submit" id="submit" value="Submit" />
</fieldset>
</form>
I want to send the results of the form in a php generated email. Everything is coming through except the selected contents of the "purpose" drop down.
Here is the PHP:
<?php
if(!$_POST) exit;
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$purpose = $_POST['purpose'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! Please enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
} else if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please enter the verification number.</div>';
exit();
} else if(trim($verify) != '4') {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "myname#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name.\r\n\n";
$e_content = "Comments: \"$comments\"\r\n\n";
$e_company = "Company: $company\r\n\n";
$e_purpose = "Reason for contact: $purpose\r\n";
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = $e_body . $e_content . $e_company . $e_purpose . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
?>
What am I missing? Thanks.

It looks like you have set an ID for your drop-down menu, but not a name. It should look like this:
<select name="purpose" id="purpose" style="width: 300px; height:35px;">
<option value="I am interested in your services">I am interested in your services!</option>
<option value="I am interested in a partnership">I am interested in a partnership!</option>
<option value="I am interested in a job">I am interested in a job!</option>
</select>

Select needs a name='purpose'

change:
<select id="purpose" style="width: 300px; height:35px;">
to:
<select id="purpose" name="purpose" style="width: 300px; height:35px;">

The "Purpose" dropdown element has an id but no name. The name controls what is sent in the POST request when the form is submitted -- items with no name are not posted.

Related

adding new field to contact.php

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

Combine Ajax Contact form and php mailer in the same script

I have created a contact form shortcode plugin for wordpress. However, the issue I am having is that I can't seem to echo the parameters of the shortcode in the php mailer file.
As an example my shortcode will look like this:
[vc-contact-form title="contact form" recipient_email="email#emailaddress.com]
The PHP code that generates this shortcode is here:
extract(shortcode_atts(array(
'el_class' => '',
'title' => '',
'subtitle' => '',
'recipient_email' => '',
), $atts));
$el_class = $this->getExtraClass($el_class);
$css_class = apply_filters(VC_SHORTCODE_CUSTOM_CSS_FILTER_TAG,$el_class, $this->settings['base']);
$subtitle = '<legend>'.$subtitle.'</legend>';
$recipient_email = '<input type="hidden" name="recipient_email" id="recipient_email" value="'.$recipient_email.'" /><br />';
$output .= '<div class="contact-form '.$css_class.'" >';
$output .= '<h4 class="form-title">'.$title.'</h4>';
$output .= '<div id="contact">
<div id="message"></div>
<form method="post" action="'. VCPB_PLUGIN_URL . 'contact.php' .'" name="contactform" id="contactform">
<fieldset>';
$output .= $subtitle;
$output .= '<label for="name" accesskey="U"><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for="email" accesskey="E"><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for="phone" accesskey="P"><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="" />
<br />
<label for="comments" accesskey="C"><span class="required">*</span> Your message</label>
<textarea name="comments" cols="40" rows="5" id="comments" style="width: 350px;"></textarea>
<p><span class="required">*</span> Are you human?</p>
<label for="verify" accesskey="V"> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />
<input type="submit" class="submit" id="submit" value="Submit" />';
$output .= $recipient_email;
$output .= '</fieldset>
</form>
</div>';
$output .= '</div>'; /* END .contact-form */
return $output;
}
}
This shortcode will output the following html:
<div class="contact-form " >
<h4 class="form-title">Contact Form</h4>
<div id="contact">
<div id="message"></div>
<form method="post" action="http://www.skizzar.com/jsdrumming/wp-content/plugins/vc-contact-form/contact.php" name="contactform" id="contactform">
<fieldset><legend>Please fill in the form below to get in touch with me</legend><label for="name" accesskey="U"><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for="email" accesskey="E"><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for="phone" accesskey="P"><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="" />
<br />
<label for="comments" accesskey="C"><span class="required">*</span> Your message</label>
<textarea name="comments" cols="40" rows="5" id="comments" style="width: 350px;"></textarea>
<p><span class="required">*</span> Are you human?</p>
<label for="verify" accesskey="V"> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />
<input type="submit" class="submit" id="submit" value="Submit" /><input type="hidden" name="recipient_email" id="recipient_email" value="sam#skizzar.com" /><br /></fieldset>
</form>
</div>
</div>
From this you can see it uses a php mailer (contact.php). The code in this is as follows:
<?php
if(!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
} else if(!isset($verify) || trim($verify) == '') {
echo '<div class="error_message">Attention! Please enter the verification number.</div>';
exit();
} else if(trim($verify) != '4') {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
$address = 'THIS NEEDS TO BE THE EMAIL ADDRESS FROM THE SHORTCODE';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$e_body = "You have been contacted by $name, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
What I am trying to do is grab the email address written in the shortcode (recipient_email) and place it in the contact.php script on this line:
$address = 'THIS NEEDS TO BE THE EMAIL ADDRESS FROM THE SHORTCODE';
I'm wondering if it's possible to combine the script that generates the shortcode html AND the php mailer, into one document as I can grab the email address easily within the shortcode script. Is this possible to do and what kind of modifications do I need to make to my script?

Using checkboxes to select the to email address in a contact form

I've created an email form that is supposed to be sent to two different email addresses depending on which check box is selected. But am having real trouble trying to make it work, Let me show you what I'm tying to do.
Baring in mind the form actually works great it's just the to email via the checkbox that's failing me.
Please Help!
This is the Form section:
<div id="respond">
<?php echo $response; ?>
<form id="commentForm" method="post" action="#contact2">
<div>
<small>Name:</small>
<input type="text" name="message_name" placeholder="Enter you name..." value="<?php echo $_POST['message_name']; ?>">
<small>Department:</small>
<!-- EDIT || replaced type=checkbox with type=radio -->
<input type="radio" name="sales" value="sales#h-s-c.co.uk" checked/>
<input type="radio"name="lettings" value="lettings#h-s-c.co.uk" />
<small>Email:</small>
<input type="text" name="message_email" placeholder="somebody#email.co.uk" value="<?php echo $_POST['message_email']; ?>">
<small>Phone:</small>
<input class="" type="tel" name="phone_number" placeholder="07912 208 936" value="<?php echo $_POST['phone_number']; ?>">
</div>
<div style="float:right;">
<small>Message:</small>
<textarea type="text" name="message_text" placeholder="I would like further information on..."><?php echo $_POST['message_text']; ?></textarea>
</div>
<small>Human Verification:</small><br>
<input type="text" style="width: 60px;" name="message_human" placeholder="2"> + 3 = 5</label>
<input type="hidden" name="submitted" value="1">
<input class="" type="submit" value="submit"/>
</form>
</div>
Then the php to send the form looks like this:
<?php
//Include email and to name
$admin_email = $_POST[$email_address];//EDIT || changed to new value $email_address
$block = "Test";
//Remove this section
//foreach($_POST['check'] as $value) {
// $checkbox .= "$value\n";
//}
?>
<?php
//response generation function
$response = "";
//function to generate response
function generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$phone = $_POST['phone_number'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = $admin_email;
$subject = "Someone sent a message from {$block}";
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$tel = 'Contact no: ' . $phone;
if(!$human == 0){
if($human != 2) generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = mail($to, $subject, $message . $tel , $headers);
if($sent) generate_response("success", $message_sent); //message sent!
else generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) generate_response("error", $missing_content);
?>
When the form is submitted checkboxes does not provide their value to the server. Check boxes only have a value on if they are checked. use a radiobutton or a select box instead.
Checkbox does not send string value, just boolean values for checkbox identifier.
Add in code a new condition
If CHECKED then use email else blank for both checkbox.
<?php
//Include email and to name
$admin_email = $_POST[$checkbox]; // no element with name 'checkbox'
$block = "Test";
// no element with name 'check'
foreach($_POST['check'] as $value) {
$checkbox .= "$value\n";
}
?>
these are main issue.
If you want to send mail to any one from the two options then use select, and in value of option provide email id
//HTML CODE
<select name="to_email">
<option value="sales#xxxx">Sales</option>
<option value="lettings#xxxx">Lettings</option>
</select>
PHP CODE
<?php
$admin_email = $_POST['to_email']; // this will get you the selected email id
?>
let me know if you have any queries.
*<form id="requestform" name="requestform" action="enquiry.php" class="col-xs-12" method="post">
<div class="form-wrapper">
<div class="col-xs-12">
<div class="field col-xs-6">
<label class="formlabel"> Email </label>
<input class="textfield" data-required="true" type="email" name="email" />
</div>
<div class="field col-xs-6">
<label class="formlabel"> Phone </label>
<input class="textfield" data-required="true" type="text" name="phone" />
</div>
</div>
<div class="clear"></div>
<div class="col-xs-12">
<div class="field col-xs-6">
<label class="formlabel"> Details </label>
<textarea class="textfield textarea" type="textarea" data-required="true" name="details"/></textarea >
</div>
<div class="field emailfunc col-xs-6">
<label class="formlabel"> What can we help you with ? </label>
<span>
<input name="interested" id="logistics" value="logistics" onchange="" type="checkbox">
<label class="inline" >Logistics</label>
</span>
<span>
<input name="interested" id="sales" value="sales" onchange="" type="checkbox">
<label class="inline" >Sales</label>
</span>
<span>
<input name="interested" id="customer" value="customer" onchange="" type="checkbox">
<label class="inline" >Customer</label>
</span>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="col-xs-12">
<div class="field col-xs-6">
<input class="submit" type="submit" value="<?php echo Mage::helper('contacts')->__('Send Enquiry') ?>" name="submit">
</div>
</div>
<div class="clear"></div>
</form>
<?php
//enquiry.php
$email=$_REQUEST['email'];
$phone=$_REQUEST['phone'];
$details=$_REQUEST['details'];
$interested=$_REQUEST['interested'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: \"Request a Quote\" <fakhruddinsouq>\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = '<html><head><title>Fakhruddin Souq</title></head><body>
<div style="color:#006A93; width:auto; height:auto; background-color:#eeeeee; margin:0px auto;">
<fieldset style=" border-color:#006A93; border-style:double;">
<legend align="center" style="font-family:Arial, Helvetica, sans-serif; font-size:18px; text-decoration:underline;">Request a Quote</legend>
<head><title>Fakhruddin Souq</title></head>
<table border="0" cellpadding="0" cellspacing="4" align="left" width="100%" height="100%" style="color:#006A93; font-weight:bold; font-size:12px; font-family:Arial, Helvetica, sans-serif;">
<td align="left" valign="top">Email: </td>
<td align="left" valign="top">'.$email.'</td>
</tr>
<tr>
<td align="left" valign="top">Phone: </td>
<td align="left" valign="top">'.$phone.'</td>
</tr>
<tr>
<td align="left" valign="top"> Product Details: </td>
<td align="left" valign="top">'.$details.'</td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" style="font-size:14px;">Regards</td>
</tr>
</table>
<span style="clear:both; float:left; font-size:14px; padding-left:4px; padding-top:10px; font-family:Arial, Helvetica, sans-serif;">Posted Date & Time:'.date('m/d/Y H:i:s').'</span>
</fieldset>
</div>
</body>
</html>';
if($interested == 'logistics') {
$to = "abc#email.com";
}
else if($interested == 'sales') {
$to = "def#email.com";
}
else if($interested == 'customer') {
$to = "imemail#email.com";
}
else if($interested == 'logistics' && $interested == 'sales' && $interested == 'customer'){
$to = "abc#email.com,def#email.com,imemail#email.com";
}
else if($interested == 'logistics' && $interested == 'sales'){
$to = "abc#email.com,def#email.com";
}
else if($interested == 'logistics' && $interested == 'customer') {
$to = "abc#email.com,imemail#email.com";
}
else if($interested == 'sales' && $interested == 'customer') {
$to = "def#email.com,imemail#email.com";
}
else {
$to ="imemail#email.com";
}
if (mail($to,'Mail From '.$name,$message,$headers)){
print json_encode(array('type'=>'done', 'text' => 'Thank You For Your Enquiry'));
exit;
}
else {
print json_encode(array('type'=>'done', 'text' => 'Sorry Email is not sent'));
exit;
}
?>*

Why is my form validation not working?

I'm having troubles validating my form. How do I validate the form using PHP? I've tried lots of different methods and nothing has worked. I can get the inputs to display (although check-box doesn't always display) but it just won't validate.
I also want to display the user's inputs (after it has been validated) onto another page, how do I do that?
Here is my code;
Form:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="" required>
<br><br>
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="" required>
<br>
<br>
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" value="" required>
<br>
<br>
Recipient:
<div>
<label for="admin">
<input type="checkbox" name="recipient[]" id="admin" value="Administrator">
Administrator</label>
<br>
<label for="editor">
<input type="checkbox" name="recipient[]" id="editor" value="Content Editor">
Content Editor</label>
<br>
</div>
<br>
<label for="message">Message:</label>
<br>
<textarea name="message" id="message" cols="45" rows="5" required></textarea>
<input type="hidden" name="submitted" value="1">
<br>
<input type="submit" name="button" id="button" value="Send">
<br>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($_POST['submitted']==1) {
if ($_POST['name']){
$name = $_POST['name'];
}
else{
echo "<p>Please enter a name.</p>" ;
}
if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email))
$email = $_POST['email'];
}
else{
echo "<p>Please enter a valid email.</p>";
}
if ($_POST['subject']){
$subject = $_POST['subject'];
}
else{
echo "<p>Please enter a subject.</p>";
if(empty($_POST['recipient'])){
echo "<p>Please select a recipient</p>";
}else{
for ($i=0; $i < count($_POST['recipient']);$i++) {
echo $_POST['recipient'][$i] . " ";
}
}
}
if ($_POST['message']){
$message = $_POST['message'];
}
/* go to form.php
display results
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong> ";
echo "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
*/
?>
if (preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)#[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,3})$/i", $email)
You can't use email in this condition because $email is empty!

PHP Form Submit Without Refresh

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.

Categories