noob: display err_msg on page - php

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>

Related

How Can I show array content inside the body of html

This is my custom user registration form WordPress site, actually, this is my first custom development, and here all the data passes the DB my problem is I need to show my error message inside the HTML code. how can I do it? can anyone help me to solve this problem? now my error messages show like this (Array ( [username_empty] => Needed Username [email_valid] => Email has no valid value [texnumber_empty] => Needed Tax Number )) but I need only show error message only Ex: this one ( [username_empty] => Needed Username) I need to show "Needed Username"
Like this.
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
$error = array();
if (strpos($username, ' ') !== FALSE) {
$error['username_space'] = "Username has Space";
}
if (empty($username)) {
$error['username_empty'] = "Needed Username";
}
if (username_exists($username)) {
$error['username_exists'] = "Username already exists";
}
if (!is_email($email)) {
$error['email_valid'] = "Email has no valid value";
}
if (email_exists($email)) {
$error['email_existence'] = "Email already exists";
}
if (empty($taxnumber)) {
$error['texnumber_empty'] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$error['password'] = "Password didn't match";
}
if (count($error) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($error);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($error as $error) {
echo $error . "<br>";
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};
This is my code I will try many times but I can't get the error messages inside the HTML body.
You want to make an AJAX call to register a user then use a callback function to check for success. If a field is invalid you also check it with javascript.
So you would need to refactor your code, seperate it into frontend/backend code and connect it via AJAX.
Write your PHP code as "add_action_hook" and register function
Onclick validate fields and inputs
Call the hook via AJAX (url: "/wp-admin/admin-ajax.php")
Return result
These are just very abstract steps, you'll need to gather some intel for yourself. You could take a look at this: https://awhitepixel.com/blog/wordpress-use-ajax/ and https://docs.wpvip.com/technical-references/security/validating-sanitizing-and-escaping/
I would do something like this
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
if (strpos($username, ' ') !== FALSE) {
$errorMsg[] = "Username has Space";
}
if (empty($username)) {
$errorMsg[] = "Needed Username";
}
if (username_exists($username)) {
$errorMsg[] = "Username already exists";
}
if (!is_email($email)) {
$errorMsg[] = "Email has no valid value";
}
if (email_exists($email)) {
$errorMsg[] = "Email already exists";
}
if (empty($taxnumber)) {
$errorMsg[] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$errorMsg[] = "Password didn't match";
}
if (count($errorMsg) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($errorMsg);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($errorMsg as $error) {
?>
<div>
<strong><?= $error; ?> </strong>
</div>
<?php
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};

PHP-validation error message doesn’t go after the user refresh the page

Problem is: If I write the wrong input for example: under username the number of character must be from 2-25 and I write only one character then error is shown and after I refresh the page the error doesn't go. How to remove the validation error after I refresh the page. There are three files: register.php Account.php and register-handlers.php
register.php
<!DOCTYPE html>
<?php
include("includes/classes/Accounts.php");
$account1 = new Accounts();
include("includes/handlers/register-Handlers.php");
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Register your free account</title>
</head>
<body>
<div id="inputContainer">
<form id="loginForm" action="login.php" method="POST">
<h2> Login to your account</h2>
<p>
<label for="loginusername">Username</label>
<input type="text" id="loginusername" placeholder="eg:shaahil" required>
</p>
<p>
<label for="loginpassword">password</label>
<input type="password" id="loginpassword" placeholder="type your password" required>
</p>
<button type="submit" name="LOGINB">Login</button>
</form>
</div>
<form id="registerpage" action="register.php" method="POST">
<h2>Create your free account</h2>
<p>
<?php echo $account1 -> getError("the character must be between 5 to 25 "); ?>
<label for="username1">Username</label>
<input type="text" name="username1" id="username1" placeholder="username" required>
</p>
<p>
<?php echo $account1->getError("your first name must have character between 2 to 25 ");?>
<label for="firstname">First name</label>
<input name="firstname" type="text" id="firstname" placeholder="eg:shaahil" required>
</p>
<p>
<?php echo $account1->getError("your last name must have character between 2 to 25 ");?>
<label for="lastname">Last name</label>
<input name="lastname" type="text" id="lastname" placeholder="eg:abraham" required>
</p>
<p>
<?php echo $account1->getError("invalid password ");?>
<?php echo $account1->getError("abc");?>
<?php echo $account1->getError("the password must be between 5 to 25 characters");?>
<label for="password">Password</label>
<input name="password" type="password" id="password" placeholder="enter your password" required>
</p>
<p>
<label for="password1">Confirm password</label>
<input name="password1" id="password1" type="password" placeholder="Confirm your password" required>
</p>
<p>
<?php echo $account1->getError("Email is invalid");?>
<label for="email1">Email</label>
<input name="email1" type="email" id="email1" placeholder="enter your email" required>
</p>
<button type="submit" name="Registerbutton">Register</button>
</form>
</body>
</html>
register-handlers.php
<?php
function sanitizeFormUsername($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormString($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormEmail($inputText){
$inputText=strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
return $inputText;
}
function sanitizeFormPassword($inputText){
$inputText=strip_tags($inputText);
return $inputText;
}
if(isset($_POST['Registerbutton'])){
$username1 = sanitizeFormUsername($_POST['username1']);
$firstname = sanitizeFormUsername($_POST['firstname']);
$lastname = sanitizeFormUsername($_POST['lastname']);
$email1 = sanitizeFormEmail($_POST['email1']);
$password= sanitizeFormPassword($_POST['password']);
$password1= sanitizeFormPassword($_POST['password1']);
$wasSuccessful = $account1->register($username1, $firstname, $lastname, $email1, $password, $password1);
if($wasSuccessful==true){
header("Location: index.php");
}
?>
Accounts.php
<?php
class Accounts{
private $errorArray;
public function __construct(){
$this->errorArray = array();
}
public function register($un1, $fn1, $ln, $em, $ps, $ps1)
{
$this->validateusername($un1);
$this->validatefirstname($fn1);
$this->validatelastname($ln);
$this->validateemail1($em);
$this->validatepasswords($ps,$ps1);
if(empty($this->errorArray) == true){
return true;
}
else {
return false;
}
}
public function getError($error) {
if(!in_array($error, $this->errorArray)) {
$error = "";
}
return " <span class='errorMessage'>$error</span> ";
}
private function validateusername($un){
if(strlen($un) > 25 || strlen($un) < 5 ){
array_push($this->errorArray , "the character must be between 5 to 25 ");
return;
}
}
private function validatefirstname($fn){
if(strlen($fn) > 25 || strlen($fn) < 2){
array_push($this->errorArray , "your first name must have character between 2 to 25 ");
return;
}
}
private function validatelastname($ln){
if(strlen($ln)>25 || strlen($ln)<2){
array_push($this ->errorArray , "your last name must have character between 2 to 25 ");
return;
}
}
private function validatepasswords($ps,$ps1){
if($ps!=$ps1){
array_push($this ->errorArray , "invalid password ");
return;
}
if(preg_match('/[^A-Za-z0-9]/', $ps)) {
array_push($this->errorArray, "abc");
return;
}
if(strlen($ps)>25 || strlen($ps)<5){
array_push($this->errorArray , "the password must be between 5 to 25 characters");
return;
}
}
private function validateemail1($em1){
if(!filter_var($em1,FILTER_VALIDATE_EMAIL)){
array_push($this ->errorArray , "Email is invalid");
return;
}
}
}
?>
This is not an answer, but rather a suggestion.
You are probably better keying your errors array with something like the field name to make error message retrieval easier.
I've adapted one of your validation methods so that it's possible to add multiple errors per field:
<?php
class AccountValidator
{
public $errors;
public function validateLastname($ln)
{
if(strlen($ln)>25 || strlen($ln)<2){
$this ->errors['lastname'][] =
"Your last name must have between 2 and 25 characters.";
return false;
}
}
}
$firstname = 'X';
$lastname = 'O';
$validator = new AccountValidator;
if($validator->validateLastname($lastname) === false)
{
echo
'<ul><li>',
implode('</li><li>', $validator->errors['lastname']),
'</li></ul>';
}
Output:
<ul><li>Your last name must have between 2 and 25 characters.</li></ul>

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()" />

Parse error: syntax error, unexpected '{' in C:\wamp\www\reg.php [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
<html>
<head>
<title>
Registration
</title>
</head>
<?php
if(isset($_POST['submit buttton'])){
processForm();
}else{
displayForm();
}
/*check out this function. Here in array doesnot work*/
function validateField($fieldname,$missingfield){
if(in_array($fieldname,$missingfield)){
echo 'class = "error"';
}
}
function setValue($fieldname){
if(isset($_POST[$fieldname])){
echo $_POST[$fieldname];
}
}
function setChecked($fieldname,$fieldvalue){
if((isset($_POST[$fieldname]) and ($_POST[fieldname] == $fieldvalue)){
echo 'checked = "checked"';
}
}
function setSelected( $fieldName, $fieldValue ) {
if ( isset( $_POST[$fieldName] ) and $_POST[$fieldName] == $fieldValue ) {
echo ' selected="selected"';
}
}
function processForm(){
$requiredfields = ("firstname","lastname","password1","password2","gender");
$missingfields = array();
foreach($missingfields as $missingfield){
if((!isset($_POST[$requiredfield]) or $_POST[$requiredfield]){
$missingfields[] = $requiredfield ;
}
}
if ( $missingFields ) {
displayForm( $missingfields );
} else {
displayThanks();
}
}
function displayForm($missingfields){
<?php
<h1>Membership Form</h1>
<?php if ( $missingFields ) { ?>
<p class="error">There were some problems with the form you submitted.
Please complete the fields highlighted below and click Send Details to
resend the form.</p>
<?php } else { ?>
<p>Thanks for choosing to join The Widget Club. To register, please
fill in your details below and click Send Details. Fields marked with an
asterisk (*) are required.</p>
?>
<?php } ?>
<form action="registration.php" method="post">
<div style="width: 30em;">
<label for="firstName"<?php validateField( "firstName",
$missingFields ) ?>>First name *</label>
<input type="text" name="firstName" id="firstName"
value="<?php setValue( "firstName" ) ?>" />
<label for="lastName"<?php validateField( "lastName",
$missingFields ) ?>>Last name *</label>
<input type="text" name="lastName" id="lastName" value=
"<?php setValue( "lastName" ) ?>" />
<label for="password1"<?php if ( $missingFields ) echo
' class="error"’ ?>>Choose a password *</label>
<input type="password" name="password1" id="password1" value="" />
<label for="password2"<?php if ( $missingFields ) echo
' class="error"’ ?>>Retype password *</label>
<input type="password" name="password2" id="password2" value="" />
<label<?php validateField( "gender", $missingFields ) ?>>Your
gender: *</label>
<label for="genderMale">Male</label>
<input type="radio" name="gender" id="genderMale" value=
"M"<?php setChecked( "gender", "M" )?>/>
<label for="genderFemale">Female</label>
<input type="radio" name="gender" id="genderFemale" value=
"F"<?php setChecked( "gender", "F" )?> />
<label for="favoriteWidget">What’s your favorite widget? *</label>
<select name="favoriteWidget" id="favoriteWidget" size="1">
<option value="superWidget"<?php setSelected( "favoriteWidget",
"superWidget" ) ?>>The SuperWidget</option>
?>
</html>
On my first run of the file the in_array function doesnt seem to work.I mean functions like isset() are displayed in bold but it seems the in_array function is not detected.
The browser displays the error as:
( ! ) Parse error: syntax error, unexpected '{' in C:\wamp\www\reg.php
on line 15.
$requiredfields = ("firstname","lastname","password1","password2","gender");
This line is invalid. You should have the keyword array before the (.
In general, use a code editor that has bracket matching. This would help you find missing )}] and extra ({[ more easily. Some even include HTML tag matching in a similar way.
http://notepad-plus-plus.org/ is a good example.
function setChecked($fieldname,$fieldvalue){
if((isset($_POST[$fieldname]) and ($_POST[fieldname] == $fieldvalue)){
The second ( in if(( needs to go away.
You also need to add array in the $requiredfields = ... line:
$requiredfields = array("firstname","lastname","password1","password2","gender");
As said previously : use && , || rather than and , or. You need array('a', 'b', 'c'), you need to be very careful with upper, lower case : $fieldname is not the same as $fieldName (n/N). There are a few other elements to check this should help :
<html>
<head>
<title>Registration</title>
<style type="text/css">.error{color:#F00}</style>
</head>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
processForm();
}
else {
displayForm();
}
function validateField($error)
{
if($error)
{
return 'class="error"';
}
}
function setValue($fieldname)
{
if(isset($_POST[$fieldname]))
{
return $_POST[$fieldname];
}
}
function setChecked($fieldname,$fieldvalue)
{
if(isset($_POST[$fieldname]) && $_POST[$fieldname] == $fieldvalue)
{
return ' checked="checked"';
}
}
function setSelected( $fieldname, $fieldvalue )
{
if ( isset( $_POST[$fieldname] ) && $_POST[$fieldname] == $fieldvalue )
{
return ' selected="selected"';
}
}
function processForm()
{
$requiredfields = array("firstName", "lastName", "password1", "password2", "gender");
$missingfields = array();
$missingfields['title'] = false;
foreach($requiredfields as $requiredfield)
{
if(!isset($_POST[$requiredfield]) || empty($_POST[$requiredfield]))
{
$missingfields[$requiredfield] = true;
$missingfields['title'] = true;
}
else {
$missingfields[$requiredfield] = false;
}
}
if ($missingfields['title'])
{
displayForm( $missingfields );
}
else {
echo displayThanks();
}
}
function displayThanks()
{
return '<h1>Everything is OK !</h1>';
}
function displayForm($missingfields)
{
?>
<h1>Membership Form</h1>
<?php if ($missingfields['title']) { ?>
<p class="error">There were some problems with the form you submitted.
Please complete the fields highlighted below and click Send Details to
resend the form.</p>
<?php } else { ?>
<p>Thanks for choosing to join The Widget Club. To register, please
fill in your details below and click Send Details. Fields marked with an
asterisk (*) are required.</p>
<?php } ?>
<form action="registration.php" method="post">
<div style="width: 30em;">
<label for="firstName"<?php echo validateField( $missingfields['firstName'] ) ?>>First name *</label>
<input type="text" name="firstName" id="firstName" value="<?php echo setValue( "firstName" ) ?>" />
<br>
<label for="lastName"<?php echo validateField( $missingfields['lastName'] ) ?>>Last name *</label>
<input type="text" name="lastName" id="lastName" value="<?php echo setValue( "lastName" ) ?>" />
<br>
<label for="password1"<?php echo validateField( $missingfields['password1'] ); ?>>Choose a password *</label>
<input type="password" name="password1" id="password1" value="" />
<br>
<label for="password2"<?php echo validateField( $missingfields['password2'] ); ?>>Retype password *</label>
<input type="password" name="password2" id="password2" value="" />
<br>
<label<?php echo validateField( $missingfields['gender'] ) ?>>Your gender: *</label>
<label for="genderMale">Male</label>
<input type="radio" name="gender" id="genderMale" value="M" <?php echo setChecked( "gender", "M" )?>/>
<label for="genderFemale">Female</label>
<input type="radio" name="gender" id="genderFemale" value="F" <?php echo setChecked( "gender", "F" )?> />
<br>
<label for="favoriteWidget">What’s your favorite widget? *</label>
<select name="favoriteWidget" id="favoriteWidget" size="1">
<option value="superWidget"<?php echo setSelected( "favoriteWidget", "superWidget" ) ?>>The SuperWidget</option>
</select>
<br>
<input type="submit" value="Sign up">
</div>
</form>
<?php } ?>
</html>
Hope it helps.

noob: display err_msg on page (pt. 2)

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.

Categories