noob: display err_msg on page (pt. 2) - php

I posted this yesterday, so I apologize if you responded and are frustrated at seeing this again! But the form isn't working at all now, and I'd appreciate some help in solving this problem.
I have a form that sends data to a database, and requires validation. Yesterday it was at least validating correctly, but today I can't even get it to hook to my action page correctly. Here are the two pages:
Page w/ form:
<?php
session_start();
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]='';}
if(!empty($_SESSION['profiledata'])){
$profiledata = $_SESSION['profiledata'];
}
?>
[js]
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v4.0
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
errors += addValidation("req","first_name","- First Name is required.");
errors += addValidation("req","last_name","- Last Name is required.");
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
}
errors += addValidation("req","security_code","- Security Code is required.");
if(!errors){
errors += addValidation("valid_lastname","first_name","- Please enter valid First Name");
errors += addValidation("valid_lastname","last_name","- Please enter valid Last Name");
errors += addValidation("numhyphenbrace","phone number","- Please enter valid Phone Number");
errors += addValidation("valid_url","web address","- Please Enter Valid Web Address");
errors += addValidation("email","email address","- Please Enter Valid Email");
}
if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
}
[/js]
<h1>Some content</h1>
<p>Some text</p>
<form id="form1" name="form1" method="post" action="mailform" onsubmit="MM_validateForm('Name','','R','Business Name','','R','Email Address','','R','How selling product','','R','Where did you hear about us','','R');return document.MM_returnValue">
<div style="color:#FF0000; text-align:center;"><?php if(!empty($_GET['err_msg'])){echo $_GET['err_msg'];} ?></div>
<fieldset>
<legend>Contact form</legend>
<p class="first">
<label for="name">First Name</label>
<input type="text" name="First Name" id="first_name" size="30" value="<?=htmlentities($profiledata['First_Name'])?>" />
</p>
<p class="first">
<label for="name">Last Name</label>
<input type="text" name="Last Name" id="last_name" size="30" value="<?=htmlentities($profiledata['Last_Name'])?>" />
</p>
<p>
<label for="name">Phone Number</label>
<input type="text" name="Phone Number" id="phone number" size="30" value="<?=$profiledata['Phone_Number']?>" />
</p>
<p>
<label for="email">Business Name</label>
<input type="text" name="Business Name" id="business name" size="30" value="<?=htmlentities($profiledata['Business_Name'])?>" />
</p>
<p>
<label for="email">Web Address</label>
<input type="text" name="Web Address" id="web address" size="30" value="<?=$profiledata['Web_Address']?>" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="Email Address" id="email address" size="30" value="<?=$profiledata['Email_Address']?>" />
</p>
</fieldset>
<fieldset>
<p>
<label for="message">Describe how you plan on selling this product</label>
<textarea name="How selling product" id="How selling product" cols="30" rows="4"><?=htmlentities($profiledata['How_selling_product'])?></textarea>
</p>
<p>
<label for="message">Where did you hear about us?</label>
<textarea name="Where did you hear about us" id="Where did you hear about us" cols="30" rows="4"><?=htmlentities($profiledata['Where_did_you_hear_about_us'])?></textarea>
</p>
<p>
<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
</p>
</fieldset>
<p class="submit"><button type="submit">Send</button></p>
<input name="mailform_address" type="hidden" value="email#address.com" />
</form>
Mailform.php success:
<?php
session_start();
include("connect.php");
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
function is_url($str)
{
return ( ! preg_match("/^((www)\.)?((\w+|[\d]?+)+(\.|\-)(\w+[\d]?+))+(\w)$/", $str)) ? FALSE : TRUE;
}
function valid_phone($str)
{
$Num = $str;
$Num = ereg_replace("([ ]+)","",$Num);;
$Num = eregi_replace("(\(|\)|\-|\+)","",$Num);
if(!is_numeric($Num))
{
return FALSE;
}
else
return TRUE;
}
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]=trim($_POST[$key]);}
$_SESSION['profiledata'] = $profiledata;
$emailto = NULL;
$emailmessage = "Dealer Contact Form\n";
$emailsubject = "Dealer Contact Form";
if(!empty($_POST)){
//echo "<pre>";print_r($_POST);die;
if( $_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'] ) ) {
// Insert your code for showing an error message here
$err_msg = 'Sorry, you have provided an invalid security code';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
} else {
unset($_SESSION['security_code']);
}
$fname = html_entity_decode(trim($_POST['First_Name']));
$lname = html_entity_decode(trim($_POST['Last_Name']));
$company = html_entity_decode(trim($_POST['Business_Name']));
$phone = html_entity_decode(trim($_POST['Phone_Number']));
$website = html_entity_decode(trim($_POST['Web_Address']));
$email = html_entity_decode(trim($_POST['Email_Address']));
$notes = "Lead Source: ".html_entity_decode(trim($_POST['Where_did_you_hear_about_us']))."\n";
$notes .= "Selling Method: ".html_entity_decode(trim($_POST['How_selling_product']));
if(!valid_phone($phone)){
$err_msg = 'Please enter valid Phone Number.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!is_url($website)){
$err_msg = 'Please enter valid Web Address.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!valid_email($email)){
$err_msg = 'Please enter valid Email.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!stristr($website,"http://") && !stristr($website,"https://") && $website){
$website = "http://".$website;
}
$res = mysql_query("SELECT in_customer_id FROM tbl_customer WHERE st_company_name = '".addslashes($company)."'");
if(mysql_num_rows($res)){
$err_msg = 'Business Name already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$res = mysql_query("SELECT st_user_name,st_user_email_id FROM tbl_admin_user WHERE st_user_email_id='".addslashes($email)."' AND flg_is_delete=0");
if(mysql_num_rows($res)){
$err_msg = 'Email already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$sql_customer = "INSERT INTO tbl_customer (`st_company_name`, `in_customer_type`, `st_customer_account`, `in_customer_phone_number`, `flg_customer_account_type`, `flg_disable_ordering`, `st_message`, `in_status`, `dt_added_date`, `st_web`, `st_notes`) VALUES ('".addslashes($company)."', '2', '".time()."', '".addslashes($phone)."', '0', '1', 'You are an Inquiry customer', '0', '".date("Y-m-d H:i:s")."', '".addslashes($website)."', '".addslashes($notes)."')";
mysql_query($sql_customer);
$cust_id = mysql_insert_id();
if($cust_id){
$sql_user = "INSERT INTO tbl_admin_user (`st_user_first_name`, `st_user_last_name`, `st_user_company_name`, `st_user_email_id`, `in_customer_id`) VALUES ('".addslashes($fname)."', '".addslashes($lname)."', '".addslashes($company)."', '".addslashes($email)."', '".$cust_id."')";
mysql_query($sql_user);
$msg = "";
$sub = "Thank you for contacting us.";
ob_start();
include("mailformat.php");
$msg = ob_get_contents();
ob_end_clean();
$headers = '';
//$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: " . $_POST['mailform_address'] . "\r\n";
$headers .= "Reply-To: ". $_POST['mailform_address'] . "\r\n";
$headers .= "Bcc: email#address.com";
if (#mail($email, $sub, $msg, $headers))
{
session_unset('profiledata');
}
}
foreach($_POST as $name => $value)
{
if ($name == 'mailform_address')
{
$emailto = $value;
}
elseif($name != "security_code")
{
$emailmessage .= $name . ": " . $value . "\n";
}
}
session_unset('profiledata');
}
?>
<?
if (#mail($emailto, $emailsubject, $emailmessage))
{
?>
<p>We'll be in touch within two business days. If you haven't heard back from us within two business days, please contact us</p>
<?
}
else
{
?>
<p>E-mail could not be sent. Please contact us.</p>
<?
}
?>
Thanks for helping me out.

I admit that I haven't read your code thoroughly, but any of these might be your problem:
In the call to MM_validateForm() in your script, I think you need to pass the names of your HTML form fields but though every argument seems correct, the first one is 'Name' that doesn't seem to be a valid form field.
What is the function addValidation() in MM_validateForm() and what does it do? Since I do not see its definition, I assume it might be generating errors in your JS.
In MM_validateForm(), after line no. 3 & 4, it seems that the variable errors is never empty and thus preventing your form to submit?
I'm not very clear at which point are you stuck - is your form not submitting at all? Did you try to do an alert of errors variable at the end of MM_validateForm(). Perhaps it might help.

Related

Need Custom WordPress Form to Send All Fields in Body of Email

I have been looking for an HTML5 compliant and accessible form plugin for a site, but there is not one out there so I ended up coding one myself (from info I have found here). It works, but I want to be able to have all fields sent in the body of the email upon submission. This just sends the message from the textarea. I'm not an expert in PHP so the answer isn't obvious to me. I appreciate any help!!
<pre>
<?php
function html_form_code()
{
?>
<form action="<?php esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
<label for="url" class="hidden">URL</label>
<input type="url" name="url" id="url" class="hidden" />
<label for="cf-name">Name*</label>
<input type="text" name="cf-name" id="cf-name" placeholder="Name" pattern="[^.]*" value="<?php isset($_POST['cf-name']) ? esc_attr($_POST['cf-name']) : ''; ?>" />
<label for="cf-email">Email*</label>
<input type="email" name="cf-email" id="cf-email" placeholder="Example: name#domain.com" value="<?php isset($_POST['cf-email']) ? esc_attr($_POST['cf-email']) : ''; ?>" />
<label for="cf-phone">Phone</label>
<input type="tel" name="cf-phone" id="cf-phone" placeholder="123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" />
<label for="cf-message">How Can We Help You?*</label>
<textarea rows="4" name="cf-message" id="cf-message" placeholder="Your Message"><?php isset($_POST['cf-message']) ? esc_attr($_POST['cf-message']) : ''; ?></textarea>
<input type="submit" name="cf-submitted" value="SEND"/>
</form>
<?php
}
// Form validation
function my_validate_form()
{
$errors = new WP_Error();
if (isset($_POST[ 'url' ]) && $_POST[ 'url' ] !== '') {
$errors->add('cheater', 'Ignore this text box. It is used to detect spammers. If you enter anything into it, your message will not be sent.');
}
if (isset($_POST[ 'cf-name' ]) && $_POST[ 'cf-name' ] == '') {
$errors->add('name_error', 'Please tell us your name.');
}
if (isset($_POST[ 'cf-email' ]) && $_POST[ 'cf-email' ] == '') {
$errors->add('email_error', 'Please fill in a valid email.');
}
if (isset($_POST[ 'cf-message' ]) && $_POST[ 'cf-message' ] == '') {
$errors->add('message_error', 'Please send us a message.');
}
return $errors;
}
// Form delivery
function deliver_mail($args = array())
{
$defaults = array(
'name' => '',
'email' => '',
'phone' => '',
'to' => get_option('admin_email'), // can change this to an email address
);
$args = wp_parse_args($args, $defaults);
$headers = "From: {$args['name']} <{$args['email']}>"."\r\n";
$subject = "Website Inquiry";
// Send email returns true on success, false otherwise
if (wp_mail($args['to'], $subject, $args['message'], $headers)) {
return;
} else {
return false;
}
}
// Form Sanitize
function my_sanitize_field($input)
{
return trim(stripslashes(sanitize_text_field($input)));
}
// Success Message
function my_form_message()
{
global $errors;
if (is_wp_error($errors) && empty($errors->errors)) {
echo '<div class="cf-success">';
echo '<p>Thank you for contacting us '.$_POST['cf-name'].', we will be in touch with you soon.</p>';
echo '</div>';
//Empty $_POST because we already sent email
$_POST = '';
} else {
if (is_wp_error($errors) && !empty($errors->errors)) {
$error_messages = $errors->get_error_messages();
foreach ($error_messages as $k => $message) {
echo '<div class="cf-error '.$k.'">';
echo '<p>'.$message.'</p>';
echo '</div>';
}
}
}
}
// Form shortcode
add_shortcode('gr_contact_form', 'cf_shortcode');
function cf_shortcode()
{
ob_start();
my_form_message();
html_form_code();
return ob_get_clean();
}
// Error validation
add_action('init', 'my_cf_form');
function my_cf_form()
{
if (isset($_POST['cf-submitted'])) {
global $errors;
$errors = my_validate_form();
if (empty($errors->errors)) {
$args = array(
'name' => my_sanitize_field($_POST['cf-name']),
'email' => my_sanitize_field($_POST['cf-email']),
'message' => my_sanitize_field($_POST['cf-message']),
);
deliver_mail($args);
} else {
return $errors;
}
}
}
?>
</pre>

Custom Contact Form with simple Math Captcha

I have a well working contact form on my site. Now I'm trying to include a math captcha to the from. Unfortunately, I was not able to make it work. Any idea how (where) to include the captcha codes?
I tried a lot of things, but it does not work properly. Maybe the code is not the best :) I already searched for a solution in stackoverflow and google with no luck.
My working contact form at the moment:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = sprintf( __( 'Please enter your name.', 'test_theme' ) );
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = sprintf( __( 'Please enter your email address.', 'test_theme' ) );
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = sprintf( __( 'You entered an invalid email address.', 'test_theme' ) );
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = sprintf( __( 'Please enter a message.', 'test_theme' ) );
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = sprintf( __( 'Contact Form', 'test_theme' ) );
$body = "Name: $name \n\nMail: $email \n\n $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p><?php _e( 'Thanks, your email was sent successfully.', 'test_theme' ); ?></p>
</div>
<?php } else { ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error-conform"><?php _e( 'Sorry, an error occured.', 'test_theme' ); ?><p>
<?php } ?>
<form action="<?php the_permalink(); ?>" class="author-description" id="contactForm" method="post">
<h2><?php _e( 'Contact Us', 'test_theme' ); ?></h2><br />
<p><label for="contactName"><?php _e( 'Your Name', 'test_theme' ); ?> <span>*</span>
<?php if($nameError != '') { ?>
<span class="error-conform"><?=$nameError;?></span>
<?php } ?><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" /></label></p>
<p><label for="email"><?php _e( 'Your Email Adress', 'test_theme' ); ?> <span>*</span>
<?php if($emailError != '') { ?>
<span class="error-conform"><?=$emailError;?></span>
<?php } ?><br />
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" /></label></p>
<p><label for="commentsText"><?php _e( 'Your Message', 'test_theme' ); ?> <span>*</span>
<?php if($commentError != '') { ?>
<span class="error-conform"><?=$commentError;?></span>
<?php } ?><br />
<textarea type="text" name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea></label></p>
<p><input type="submit"></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
Captcha Code that should included in the contact form above:
Part 1:
if(!isset($_POST['submitted'])) {
session_start();
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
}
Part 2:
if ($_SESSION['answer'] != $_POST['answer'] ) {
$mathError = 'Please answer the math question.';
$hasError = true;
}
Part 3:
<span class="error-conform"><?=$mathError;?></span>
<li><label>What's <?php echo $math; ?> = </label><input name="answer" type="text" /></li>
I guess this will give you some ideas.
<?php
session_start(); // session start should be the very first line of your php code, for session management
// checking whether the form is being submitted by the user
if( isset($_POST['submitted']) )
{
// checking whether the user submitted answer matches with the captcha
if ($_SESSION['answer'] != $_POST['answer'] )
{
$mathError = 'Please answer the math question.';
$hasError = true;
}
// ....
// do other form validations here..
// ....
if( !$hasError )
{
// no errors, so send the mail or do whatever you want to do here...
}
}
// now generating new captcha
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
?>
<!-- html goes here --->
<forma ction="<?php the_permalink(); ?>
<!-- include the form fields here... -->
<?php if(!empty($mathError)) { ?>
<span class="error-conform"><?php echo $mathError; ?></span>
<?php } ?>
<label>What's <?php echo $math; ?> = </label><input name="answer" type="text" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<!-- rest of the html goes here --->

Reset form fields after form submission in wordpress custom contact form plugin

I've my own custom contact form wordpress plugin, in which I'm unable to reset the form fields after the user submits the form.
When the user fills up all the fields and submits, success message will be shown, and after that I need the form to reset all the fields. At present it shows the values entered by the user before submission.
Any help is greatly appreciated. Thanks in advance. Here is my code.
<?php
/*
Plugin Name: Custom Contact Form
Plugin URI:
Description: <code>[contact email="your#email.address"]</code>
Version: 1.0
Author:
Author URI:
*/
// function to get the IP address of the user
function tw_get_the_ip() {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
return $_SERVER["HTTP_CLIENT_IP"];
}
else {
return $_SERVER["REMOTE_ADDR"];
}
}
// the shortcode
function tw_contact_form_sc($atts) {
extract(shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"subject" => '',
"label_name" => 'Your Name',
"label_email" => 'Your E-mail Address',
"label_subject" => 'Subject',
"label_message" => 'Your Message',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("your_name", "email", "message", "subject");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "[" . get_bloginfo('name') . "] " . $form_data['subject'];
$email_message = $form_data['message'] . "\n\nIP: " . tw_get_the_ip();
$headers = "From: ".$form_data['your_name']." <".$form_data['email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
wp_mail($email, $email_subject, $email_message, $headers);
$result = $success;
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" action="'.get_permalink().'">
<div>
<label for="cf_name">'.$label_name.':</label>
<input type="text" name="your_name" id="cf_name" size="50" maxlength="50" value="'.$form_data['your_name'].'" />
</div>
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" />
</div>
<div>
<label for="cf_subject">'.$label_subject.':</label>
<input type="text" name="subject" id="cf_subject" size="50" maxlength="50" value="'.$subject.$form_data['subject'].'" />
</div>
<div>
<label for="cf_message">'.$label_message.':</label>
<textarea name="message" id="cf_message" cols="50" rows="15">'.$form_data['message'].'</textarea>
</div>
<div>
<input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info.$email_form;
} else {
return $info.$email_form;
}
} add_shortcode('contact', 'tw_contact_form_sc');
?>
In this instance you can just manually assign your values on $sent == true:
// Presumably if the email is sent, you want blank values instead
// of populated ones.
if($sent == true) {
$form_data['your_name'] = "";
$form_data['email'] = "";
$form_data['subject'] = "";
$form_data['message'] = "";
}
$email_form = '<form class="contact-form" method="post" action="'.get_permalink().'">
<div>
<label for="cf_name">'.$label_name.':</label>
<input type="text" name="your_name" id="cf_name" size="50" maxlength="50" value="'.$form_data['your_name'].'" />
</div>
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" />
</div>
<div>
<label for="cf_subject">'.$label_subject.':</label>
<input type="text" name="subject" id="cf_subject" size="50" maxlength="50" value="'.$subject.$form_data['subject'].'" />
</div>
<div>
<label for="cf_message">'.$label_message.':</label>
<textarea name="message" id="cf_message" cols="50" rows="15">'.$form_data['message'].'</textarea>
</div>
<div>
<input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
There are lots of ways to do this, but without doing much in the way of modifying what you have, this is probably the quickest.
if you are using Ajax/Json for submit form, then after submit form put a simple code in ajax/json
$('form').reset();
also you set a custom class for all input fields just ex. class name :clear
then use
$('.class').val('');
and simple answer is this:
<input type="submit" onClick="this.form.reset()" />

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.

noob: display err_msg on page

I have a form that populates a database, and I'm having trouble with the error handling. I want the errors to show in a small pop up window on the same pg.
<form id="form1" name="form1" method="post" action="mailform.php" onsubmit="MM_validateForm('Name','','R','Business Name','','R','Email Address','','R','How selling product','','R','Where did you hear about us','','R');return document.MM_returnValue">
<div style="color:#FF0000; text-align:center;"><?php if(!empty($_GET['err_msg'])){echo $_GET['err_msg'];} ?></div>
<fieldset>
<legend>Contact form</legend>
<p class="first">
<label for="name">First Name</label>
<input type="text" name="First Name" id="first_name" size="30" value="<?=htmlentities($profiledata['First_Name'])?>" />
</p>
<p class="first">
<label for="name">Last Name</label>
<input type="text" name="Last Name" id="last_name" size="30" value="<?=htmlentities($profiledata['Last_Name'])?>" />
</p>
<p>
<label for="name">Phone Number</label>
<input type="text" name="Phone Number" id="phone number" size="30" value="<?=$profiledata['Phone_Number']?>" />
</p>
<p>
<label for="email">Business Name</label>
<input type="text" name="Business Name" id="business name" size="30" value="<?=htmlentities($profiledata['Business_Name'])?>" />
</p>
<p>
<label for="email">Web Address</label>
<input type="text" name="Web Address" id="web address" size="30" value="<?=$profiledata['Web_Address']?>" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="Email Address" id="email address" size="30" value="<?=$profiledata['Email_Address']?>" />
</p>
<p>
<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
</p>
</fieldset>
<fieldset>
<p>
<label for="message">Describe how you plan on selling this product</label>
<textarea name="How selling product" id="How selling product" cols="30" rows="4"><?=htmlentities($profiledata['How_selling_product'])?></textarea>
</p>
<p>
<label for="message">Where did you hear about us?</label>
<textarea name="Where did you hear about us" id="Where did you hear about us" cols="30" rows="4"><?=htmlentities($profiledata['Where_did_you_hear_about_us'])?></textarea>
</p>
</fieldset>
<p class="submit"><button type="submit">Send</button></p>
<input name="mailform_address" type="hidden" value="email#address.com" />
</form>
Error handling:
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
function is_url($str)
{
return ( ! preg_match("/^((www)\.)?((\w+|[\d]?+)+(\.|\-)(\w+[\d]?+))+(\w)$/", $str)) ? FALSE : TRUE;
}
function valid_phone($str)
{
$Num = $str;
$Num = ereg_replace("([ ]+)","",$Num);;
$Num = eregi_replace("(\(|\)|\-|\+)","",$Num);
if(!is_numeric($Num))
{
return FALSE;
}
else
return TRUE;
}
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]=trim($_POST[$key]);}
$_SESSION['profiledata'] = $profiledata;
$emailto = NULL;
$emailmessage = "Dealer Contact Form\n";
$emailsubject = "Dealer Contact Form";
if(!empty($_POST)){
//echo "<pre>";print_r($_POST);die;
if( $_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'] ) ) {
// Insert your code for showing an error message here
$err_msg = 'Sorry, you have provided an invalid security code';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
} else {
unset($_SESSION['security_code']);
}
$fname = html_entity_decode(trim($_POST['First_Name']));
$lname = html_entity_decode(trim($_POST['Last_Name']));
$company = html_entity_decode(trim($_POST['Business_Name']));
$phone = html_entity_decode(trim($_POST['Phone_Number']));
$website = html_entity_decode(trim($_POST['Web_Address']));
$email = html_entity_decode(trim($_POST['Email_Address']));
$notes = "Lead Source: ".html_entity_decode(trim($_POST['Where_did_you_hear_about_us']))."\n";
$notes .= "Selling Method: ".html_entity_decode(trim($_POST['How_selling_product']));
if(!valid_phone($phone)){
$err_msg = 'Please enter valid Phone Number.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!is_url($website)){
$err_msg = 'Please enter valid Web Address.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!valid_email($email)){
$err_msg = 'Please enter valid Email.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!stristr($website,"http://") && !stristr($website,"https://") && $website){
$website = "http://".$website;
}
$res = mysql_query("SELECT in_customer_id FROM tbl_customer WHERE st_company_name = '".addslashes($company)."'");
if(mysql_num_rows($res)){
$err_msg = 'Business Name already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$res = mysql_query("SELECT st_user_name,st_user_email_id FROM tbl_admin_user WHERE st_user_email_id='".addslashes($email)."' AND flg_is_delete=0");
if(mysql_num_rows($res)){
$err_msg = 'Email already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
I'd appreciate some help or at least a nudge in the right direction. Thanks!
Depending on what kind of 'popup' you want, you will probably want to implement some client side javascript that displays a nicely formatted message that makes use of the message that you send back from the server.
I'd look at using JQuery if it was me.
Is this okay?
<html>
<head>
<script>
function Start(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,width=600,height=200,left="
+((window.screen.width-600)/2)+",top="+((window.screen.height-200)/3)+"" );
}
</script>
</head>
<body onload="Start('child.htm')">
This is parent.
</body>
</html>

Categories