Need help on css display state using localStorage and jQuery - javascript

I am building a multi-page form and it has a lot of conditional statements. Some of which deal with the display of particular DIVs based upon the selection of some other DIVs. To make my question simple I have created another form that works similarly, but is very short.
The first input field asks the "First Name." After it is filled with characters, two fields for "Middle Name," and "Last Name" appear. Originally, these two fields have "inline-style" of "display:none;" and hence are not displayed until the jQuery function displays them. Once the user fills out the form and hits submit, PHP validations run on the server.
For our purpose, let's fill the first input field then followed by two new fields displayed by jQUery, leave other fields blank and hit "submit." Of course, the PHP validations fail and we are shown the refreshed version of the form with all the form data gone and most importantly for my usage, the CSS display state for the two input fields gone. Now, I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I need help with restoring the form data on the first field followed by the display of the other two fields with their data. I sort of know how the localStorage works, but I could not make it work here.
I very much appreciate anyone giving this their time.
Once again, thank you very much.
Here goes the code:
<?php
$firstName = $middleName = $lastName = $email = $phone = $comment = $from = $name = $subject = $subject2 = $message2 = $headers = $headers2 = $result = $result2 = '';
$errors = array('firstName'=>'','middleName'=>'','lastName'=>'','email'=>'','phone'=>'','comment'=>' ');
if(isset($_POST['submit'])) { /**checks if the submit button is pressed or not. only executes below steps if the form is submitted.**/
//check first name input
if(empty($_POST['firstName'])){
$errors ['firstName'] = 'Please enter your First Name <br />';
} else {
$firstName = $_POST['firstName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $firstName)){
$errors ['firstName'] = 'Only letters are accepted <br />';
}
}
//check middle name input
if(empty($_POST['middleName'])){
$errors ['middleName'] = 'Please enter your Middle Name <br />';
} else {
$middleName = $_POST['middleName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $middleName)){
$errors ['middleName'] = 'Only letters are accepted <br />';
}
}
//check last name input
if(empty($_POST['lastName'])){
$errors ['lastName'] = 'Please enter your Last Name<br />';
} else {
$lastName = $_POST['lastName'];
if(!preg_match('/^[a-zA-Z\s]+$/', $lastName)){
$errors ['lastName'] = 'Only letters are accepted <br />';
}
}
//check email input
if(empty($_POST['email'])){
$errors ['email'] = 'Please enter your E-mail Address <br />';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors ['email'] = 'Email must be a valid email address <br />';
}
}
//check phone number input
if(empty($_POST['phone'])){
$errors ['phone'] ='Please enter your Phone Number<br />';
} else {
$phone = $_POST['phone'];
if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}+$/', $phone)){
$errors ['phone'] = 'Only numbers separated by dashes are allowed <br />';
}
}
//check comment input
if(empty($_POST['comment'])){
$errors ['comment'] = 'Please provide your feedback <br />';
} else {
$comment = $_POST['comment'];
if(!preg_match('/^[\w,.!?\s]+$/',$comment)){
$errors ['comment'] = 'Only letters, commas, and periods are allowed <br />';
}
}
if(array_filter($errors)){
//let the user fill out form again
echo '<script type = "text/javascript">alert("Submission failed due to error in the input field. Please fill all the input fields and submit the form again. Thank you!") </script>';
} else {
header('location:thank-you');
}
//php to send message to both client and the owner
$mailto = "a#b.com"; //web owners email addresss
$from = $_POST['email']; //senders email address
$name = $_POST['firstName']; //user's name
$subject = "You received a message";
$subject2 = "Your message has been submitted successfully"; //message title for client email
$comment = "Client Name: ". $firstName. "wrote the following message". "\n\n". $_POST ['comment'];
$message = "Contact Form". "\n\n".
"From - ". $firstName. " ". $middleName. " ". $lastName. "\n\n".
"Email Id - ". $from. "\n\n". "Phone Number - ". $phone. "\n\n".
"FeedBack :". "\n\n". $_POST ['comment'];
$message2 = "Dear ". $firstName. ",". "\n\n". "Thank you for contacting us!";
$headers = "From: ". $from; //user entered email address
$headers2 = "From: ". $mailto; // this will receive to client
$result = mail($mailto, $subject, $message, $headers); //send email to the website owner
$result2 = mail($from, $subject2, $message2, $headers2); //send email to the user or form submitter
} // end of POST check
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1 /jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1 /jquery.validate.min.js"></script>
<link rel="stylesheet"href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label{display:block;}
.container{display:flex; flex-direction: row; flex-wrap: wrap;
margin-top:10rem; justify-content: left; margin-left:3rem;}
.flexItems{
margin-right:1rem; margin-bottom:2rem;
}
#submit{
margin-left:3rem;
width:20em;
}
.comment{
margin-left:3rem;
}
.red-text{
color:red;
}
</style>
<script>
$(document).ready(function() {
$("#fName").change(function(){
if($(this).val() != "" ){
$("#mName1").css("display","block");
$("#lName1").css("display","block");
} else {
$("#mName1").css("display","none");
$("#lName1").css("display","none");
}
})
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete = "off" id = "form">
<div class = "container">
<div class= "flexItems">
<label>First Name</label>
<input id = "fName" type = "text" name = "firstName" >
<div class = "red-text"><?php echo $errors['firstName']; ?></div>
</div>
<div class= "flexItems" id = "mName1" style = "display:none;">
<label>Middle Name</label>
<input id = "mName" type = "text" name = "middleName" >
<div class = "red-text"><?php echo $errors ['middleName']; ?></div>
</div>
<div class= "flexItems" id = "lName1"style = "display:none;" >
<label>Last Name</label>
<input id = "lName" type = "text" name = "lastName" >
<div class = "red-text"><?php echo $errors ['lastName']; ?></div>
</div>
<div class= "flexItems">
<label>Email Address</label>
<input id = "eAddress" type = "email" name = "email" >
<div class = "red-text"><?php echo $errors ['email']; ?></div>
</div>
<div class= "flexItems">
<label>Phone Number</label>
<input id = "pNumber" type = "tel" name = "phone" >
<div class = "red-text"><?php echo $errors ['phone']; ?></div>
</div>
<div class= "comment">
<label>Comment</label>
<textarea rows = "6" cols ="60" name = "comment" placeholder = "Please leave a comment. Thank you!" ></textarea>
<div class = "red-text"><?php echo $errors ['comment']; ?></div>
</div>
<div id = "submit">
<button type= "submit" id = "submit" value = "Send my message ASAP" name = "submit">Submit</button>
</div>
</div>
</form>
</body>
</html>

I know I could add php to keep the values on the input fields, but that still does not solve my problem of keeping the CSS display state of the "display:none;" DIVs.
I would recommend using PHP to fill in the form values after submission and solve showing/hiding elements with JavaScript.
For example PHP would look like this: (using htmlspecialchars to escape quotes and other special characters and reading data directly from POST request)
<input
id="fName"
type="text"
name="firstName"
value="<?php echo htmlspecialchars($_POST['firstName']); ?>"
>
There is also possibility to keep values in localStorage if you prefer. I was able to find this jQuery plugin which does that - Persist.js.
Second task is to show/hide corresponding fields.
First of all, try to think about user experience when new fields appear or disappear. Maybe it's better to keep all the fields on the screen, disable/enable them etc. I can think of one case when fields can be hidden and it is when several options are presented for selection and the last option is 'other (please specify)' which allows to input custom response. I'll be adding this use case to the prototype bellow.
I'd recommend to create a single updateVisibility function that will show/hide needed blocks. It should be called when page loads (with data filled in with PHP) and when any form field is modified:
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") { // always use === or !== in JS for comparison
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
// hide inputs and clear values
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
});
P.S. I've noticed and fixed several errors in HTML:
tag attributes should not contain spaces - id="fName" (not id = "fName")
label tag requires for attribute - <label for="fName"> (where fName is an ID of some other element to which label will point)
Please find prototype code bellow (only HTML part, StackOverflow does not run PHP). Programming language field is an example of how I think user experience should be, I've kept Middle name/Last name fields functionality like in your question.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli">
<title>Contact Form</title>
<style>
label {
display: block;
}
label.radio-label {
display: inline;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-top: 10rem;
justify-content: left;
margin-left: 3rem;
}
.flexItems {
margin-right: 1rem;
margin-bottom: 2rem;
}
#submit {
margin-left: 3rem;
width: 20em;
}
.comment {
margin-left: 3rem;
}
.red-text {
color: red;
}
</style>
<script>
function updateVisibility() {
// fname - show/hide mName/lName
if ($("#fName").val() !== "") {
$("#mName1").css("display", "block");
$("#lName1").css("display", "block");
} else {
$("#mName1").val('').css("display", "none");
$("#lName1").val('').css("display", "none");
}
// language other - show/hide language-other-block
if ($('input[name="language"][type="radio"]:checked').val() === 'other') {
$('#language-other-block').css('display', 'block');
} else {
$('#language-other-block').css('display', 'none');
$('#language-other-input').val('');
}
}
$(document).ready(function () {
// call when page is loaded
updateVisibility()
// and every time any field changes in the form
$("#form").change(updateVisibility)
})
</script>
</head>
<body>
<form action="" method="POST" auto_complete="off" id="form">
<div class="container">
<div class="flexItems">
<label for="fName">First Name</label>
<input id="fName" type="text" name="firstName">
<div class="red-text">
<?php echo $errors['firstName']; ?>
</div>
</div>
<div class="flexItems" id="mName1" style="display:none;">
<label for="mName">Middle Name</label>
<input id="mName" type="text" name="middleName">
<div class="red-text">
<?php echo $errors ['middleName']; ?>
</div>
</div>
<div class="flexItems" id="lName1" style="display:none;">
<label for="lName">Last Name</label>
<input id="lName" type="text" name="lastName">
<div class="red-text">
<?php echo $errors ['lastName']; ?>
</div>
</div>
<div class="flexItems">
<label for="eAddress">Email Address</label>
<input id="eAddress" type="email" name="email">
<div class="red-text">
<?php echo $errors ['email']; ?>
</div>
</div>
<div class="flexItems">
<label for="pNumber">Phone Number</label>
<input id="pNumber" type="tel" name="phone">
<div class="red-text">
<?php echo $errors ['phone']; ?>
</div>
</div>
<div class="flexItems">
<div>Programming language</div>
<div><input type="radio" name="language" value="js" id="language-js"><label class="radio-label"
for="language-js">JavaScript</label></div>
<div><input type="radio" name="language" value="php" id="language-php"><label class="radio-label"
for="language-php">PHP</label></div>
<div><input type="radio" name="language" value="other" id="language-other"><label class="radio-label"
for="language-other">other</label></div>
<div id="language-other-block" style="display: none;">
<label class="radio-label" for="">Please specify: </label>
<input type="text" name="language-other" id="language-other-input">
</div>
<div class="red-text">
<?php echo $errors ['language']; ?>
</div>
</div>
<div class="comment">
<label for="comment">Comment</label>
<textarea rows="6" cols="60" id="comment" name="comment"
placeholder="Please leave a comment. Thank you!"></textarea>
<div class="red-text">
<?php echo $errors ['comment']; ?>
</div>
</div>
<div id="submit">
<button type="submit" id="submit" value="Send my message ASAP" name="submit">Submit</button>
</div>
</div>
</form>
</body>
</html>

Related

Problem with register form using JavaScript validation and PHP

I have a problem. I don't know why when I did run the HTML and javascript only (without PHP part), the validation works really well. However, when I did run the PHP with the HTML and JavaScript, the validation doesn't work. For example, when the username is 123john (everything else such as password, name,... met the requirements) which is not allowed. The form still submitted successfully (I did check the MySQL database and the user 123john is there). Can someone help me with this? Thank you for your help.
The original code structure is the PHP and HTML are in the same file, only the JavaScript is on a separate file.
<?php
session_start();
require 'connect.php';
if(isset($_POST['register'])){
$username = !empty($_POST['user_name']) ? trim($_POST['user_name']) : null;
$pass = !empty($_POST['pass']) ? trim($_POST['pass']) : null;
$firstName = !empty($_POST['first_name']) ? trim($_POST['first_name']) : null;
$lastName = !empty($_POST['last_name']) ? trim($_POST['last_name']) : null;
$collegeName = !empty($_POST['uni']) ? trim($_POST['uni']) : null;
$majorName = !empty($_POST['major']) ? trim($_POST['major']) : null;
$sql = "SELECT COUNT(user_name) AS num FROM users WHERE user_name = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('Username existed');
}
$sql = "INSERT INTO users (user_name, pass, first_name, last_name, uni, major) VALUES (:username, :password, :first_name, :last_name, :uni, :major)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $pass);
$stmt->bindValue(':first_name', $firstName);
$stmt->bindValue(':last_name', $lastName);
$stmt->bindValue(':uni', $collegeName);
$stmt->bindValue(':major', $majorName);
$result = $stmt->execute();
if($result){
echo 'Thank you for registering with our website.';
}
}
?>
var check_form=document.getElementById("registration");
var pattern=/^[a-zA-Z\s]+$/;
var patternUsername=/^[A-Za-z]\w*$/;
function check(event){
var userName=document.getElementById("username");
var passWord=document.getElementById("password");
var last_name=document.getElementById("lastName");
var first_name=document.getElementById("firstName");
var collegeName=document.getElementById("uni");
var majorName=document.getElementById("majoring");
event.preventDefault();
if(userName.value==""){
alert("User name needs to be specified");
userName.focus();
}
else{
if(!patternUsername.test(userName.value)){
alert("Invalid username");
userName.focus();
}
}
if(passWord.value==""){
alert("Password needs to be specified");
passWord.focus();
}
else{
if(passWord.length<8){
alert("Password needs to be longer than 8 characters");
passWord.focus();
}
}
if(first_name.value==""){
alert("First name needs to be specified");
first_name.focus();
}
else{
if(!pattern.test(first_name.value)){
alert("First name does not allow number");
first_name.focus();
}
}
if(last_name.value==""){
alert("Last name needs to be specified");
last_name.focus();
}
else{
if(!pattern.test(last_name.value)){
alert("Last name does not allow number");
last_name.focus();
}
}
if(collegeName.value==""){
alert("College name needs to be specified");
collegeName.focus();
}
else{
if(!pattern.test(collegeName.value)){
alert("Invalid college name");
collegeName.focus();
}
}
if(majorName.value==""){
alert("Major name needs to be specified");
majorName.focus();
}
else{
if(!pattern.test(majorName.value)){
alert("Invalid major name");
majorName.focus();
}
}
/*
if(first_name.value!=="" && last_name.value!==""&&email!==""&&pattern.test(first_name.value)&&pattern.test(last_name.value)){
alert("Perfect");
}
*/
}
check_form.addEventListener("submit",check);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<!--<link rel="stylesheet" href="./register.css">-->
<script src="./script.js" defer></script>
<style>
form div{
padding: 8px;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=PT+Sans&display=swap" rel="stylesheet">
</head>
<body>
<h1>Register</h1>
<form id="registration" action="register.php" method="post">
<div id='userName'>
<label for="username">Username: </label>
<input type="text" id="username" name="user_name"><br>
</div>
<div id="passWord">
<label for="password">Password: </label>
<input type="text" id="password" name="pass"><br>
</div>
<div id='firstname'>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="first_name"><br>
</div>
<div id="lastname">
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="last_name"><br>
</div>
<div id="uniName">
<label for="uni">College Name: </label>
<input type="text" id="uni" name="uni"><br>
</div>
<div id="majorName">
<label for="majoring">Major: </label>
<input type="text" id="majoring" name="major"><br>
</div>
<br>
<input type="submit" name="register" value="Register"><br><br>
Already have an account?
</form>
</body>
</html>
If you want to do your client-side validation. you must change the type of the button from (send) to (button). Then, create a function in JS to validate your form.
Call the function by clicking onclick button = "ItsFunctionForValidateAndSubmit ()".
After checking: Create a form submission method using javascript.
Here is a link to some sample form submissions.
Send POST data using XMLHttpRequest
<input type="buttom" name="register" value="Register" onclick="ItsFunctionForValidateAndSubmit()">

Make select options disable after submitting the form

I've been trying this for awhile. I appreciate your help.
I've a form with two fields. 1- Username. 2- City.
Users can select their cities from the city select options (the cities come from the database).
However, if the user didn't find his/her city, he/she can check the checkbox to enable a text input to enter his/her city (and at the same time the select options will be disable).
The issue is, if the user writes new city, the select options will be disable (this is good), but when the user submits the form a and there was a validation issue (for example: empty username!), the form will go back with the following:
The city select options will be enable !!
The city text input will be disable (with sticky city name that the user entered) !!
So, how can I keep the city name in the text input enable with the value, and make the city select options disable??
This is my code:
<title> Form </title>
<link rel="icon" type="image/png" href="images/icon/anta_ana.png">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<div id="page-wrapper">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$city_name = $_POST['city_name'];
//errors handling :
$error = array();
if(empty($username)) $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please write your name!
</div>";
if($city_name == 'all') $error[]= "<div class='alert alert-danger alert-dismissible input-sm' role='alert' dir='rtl' style='padding-top: 5px; padding-right: -5px; padding-bottom: 0px; padding-left: 0px'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
<strong style='color: #e62e00;'>Warning!</strong> Please selects a city!
</div>";
if(empty($error)) {
include("dbc.php");
$q = "INSERT INTO users (username,
city_name) VALUES
('$username',
'$city_name')";
$r = mysqli_query($dbc, $q);
if($r){
echo "<script>window.open('successfully_registered.php', '_self')</script>";
}
else{
echo "error";
}
}
else{
foreach ($error as $err){
echo $err;
}
}
}
?>
<form action="question.php" method="POST" name="" dir="rtl">
<!-- Userame -->
<div class="form-group">
<label class="control-label" style="float: right;"> Username </label>
<input type="text" class="form-control" placeholder="Username" name="username" value =
<?php if(isset($_POST['username'])) echo $_POST['username'] ?>>
</div>
<!-- City -->
<div class="form-group">
<label style="float: right;">City </label>
<?php
include("dbc.php");
$qm = "SELECT DISTINCT city_name FROM cities ORDER BY city_name";
$rm = mysqli_query($dbc,$qm);
while ($row = mysqli_fetch_array($rm)){
$cities_array[] = $row['city_name'];
}
echo '<select class="form-control border-input" name="city_name" id="city_name">';
echo '<option value="all"> All </option>';
foreach($cities_array as $cities){
$selected = '';
if($_POST['city_name'] == $cities) {
$selected = 'selected="selected"';
}
echo '<option value="'.$cities.'"'.$selected.'>'.$cities.'</option>';
}
echo '</select>';
?>
</div>
<!-- Another City? -->
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value =
"<?php if (isset($_POST['new_city'])) echo $_POST['new_city']; ?>" >
<script>
document.getElementById('another_city').onchange = function() {
document.getElementById('new_city').disabled = !this.checked;
if(document.getElementById('new_city').disabled){
$("#city_name").prop('disabled', false);
}
else{
$("#city_name").prop('disabled', true);
}
};
</script>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info btn-fill form-control" name="submit" value="Send"><i class="fa fa-paper-plane"></i> Send </button>
</div>
</form>
</div>
if you want to disable Select just use this code
$('select').attr('disabled','disabled');
first of all: your code is (principally) vulnerable to sql injection,
http://php.net/manual/de/security.database.sql-injection.php
second: the reason is fairly simple, you submit your form, check it in the BACKEND and redirect. The reason why option is enabled and textbox disabled is simply because the page is reloaded, and thats your default setting. you could pass a parameter indicating the failure in your url (like err=wrongArgument) or whatever) and disable the options box with javascript in that case.
If the problem only occurs because of validation you can first submit the form details via an ajax request. validate it and if there are no errors then submit them. If you were using jquery then you could do something like
$("#form-id").submit(function(e){
e.preventDefault();
$.ajax({
method: 'POST',
url: 'validate.php',
data: $(this).serialize(),
success: function(res){
if(res == "success") {
$(this).submit();
} else { // error }
},
fail: function(){
// error
}
})
})
one other thing that you could do is if you redirect to the current page after validation fails and pass a query string at the end that denotes that the user checked the checkbox or not. you have to give your checkbox a name for this so it gets submitted over as well when you submit the form.
if(isset($_POST['another_city']) and $_POST['another_city'] == "on") {
// header("Location: ...") redirects the page to the provided location
header("Location: question.php?checked=1"&city=".$city_name);
}
once you do this you will have to add code to check whether the $_GET['checked'] and $_GET['city'] are set or not. if they are set then you can set the provided values in the form using js like:
php:
$checked = "";
$city = "";
if(isset($_GET['checked']) and $_GET['checked'] == 1) {
$checked = "checked";
}
if(isset($_GET['city'])) {
$city= $_GET['city'];
}
html:
<div class="form-group">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i> Didn't find you city? Check this box to enter your city: <input type="checkbox" <?php echo $checked?> id="another_city"/>
<input placeholder="Write your city here" class="form-control" type="text" name="new_city" id="new_city" disabled value = "<?php echo $city; ?>" >

php mail() sending mail before form is filled

I have a self posting document that has form fields to fill out with php processing on the same document. My problem is that upon opening the page (website), the message "Message Sent!" shows up immediately before the form can be filled out with information. The php mail() function is linked to my email account so I get the form data email. But no data is sent because the email was sent before the form could be filled out. I want to be able to fill out the form before the email is sent off so that way the form sends actual information. Ive researced this topic and came up with nothing. Any help would be awesome! Here's my code...
<?php
foreach($_POST as $key => $value) //This will loop through each name-value in the $_POST array
{
$tableBody .= "<tr>"; //formats beginning of the row
$tableBody .= "<td>$key</td>"; //dsiplay the name of the name-value pair from the form
$tableBody .= "<td>$value</td>"; //dispaly the value of the name-value pair from the form
$tableBody .= "</tr>"; //End this row
}
echo "<table border='1'>";
echo "<tr><th>Field Name</th><th>Value of field</th></tr>";
foreach($_POST as $key => $value)
{
echo '<tr class=colorRow>';
echo '<td>',$key,'</td>';
echo '<td>',$value,'</td>';
echo "</tr>";
}
echo "</table>";
echo "<p> </p>";
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
background-image: url("rbGrid.png");
background-size: 150%;
background-repeat: no-repeat;
text-align: center;
}
div {
background-color: black;
opacity: 0.9;
color: white;
text-align: center;
}
h1 {
color: white;
}
h2 {
color: white;
}
#borderStyle {
border: double thick red;
border-radius: 45px;
width: 50%;
margin: 0 auto;
}
#hiddenStuff {
display: none;
}
textarea {
display: none;
margin: 0 auto;
}
#mailingInformation {
display: none;
margin: 0 auto;
}
table {
margin: 0 auto;
border: solid thick red;
border-radius: 20px;
}
th {
border: solid thick red;
border-radius: 45px;
}
tr {
color: white;
border: solid thin red;
border-radius: 45px;
}
td {
color: white;
border: solid thin red;
border-radius: 45px;
}
</style>
<script>
function showProductProblemComments()
{
document.getElementById("textarea").style.display = "block";
}
function showMailingListForm()
{
document.getElementById("mailingInformation").style.display = "block";
}
</script>
</head>
<body>
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
/*$inName = $_POST["Name"];
$inEmail = $_POST["Email Address"];
$inAddress = $_POST["address"];
$inReason = $_POST["Reason"];
$inComments = $_POST["comments"];
$inMailBox = $_POST["Mailing List"];
$inUseAddress = $_POST["checkForAddress"];
$inFirstName = $_POST["mailingName"];
$inLastName = $_POST["mailingLastName"];
//$inMailingAdd $_POST["mailingAddress"];
$inPhoneNumber = $_POST["phoneNumber"];
$inMoreInfo = $_POST["More Info"];*/
?>
<h1>WDV341 Intro PHP</h1>
<h2>Programming Project - Contact Form</h2>
<div>
<form name="form1" method="POST" action="contactForm2.php">
<p> </p>
<p>
<div id = "borderStyle">
<label>Your Name:
<input type="text" name="Name" id="textfield" required>
</p>
<br><br>
<p>Your Email:
<input type="text" name="Email Address" id="textfield2" required>
</p>
<br><br>
<p>Your Address:
<input type = "text" name = "address" id = "living">
</p>
<br><br>
<p>Reason for contact:
<select name="Reason" id="select2" onChange = "showProductProblemComments()" required>
<option value="default">Please Select a Reason</option>
<option value="product">Product Problem</option>
<option value="return">Return a Product</option>
<option value="billing">Billing Question</option>
<option value="technical">Report a Website Problem</option>
<option value="other">Other</option>
</select>
</p>
<br><br>
<p>Comments:
<textarea name="comments" id="textarea" cols="45" rows="5"required></textarea>
</p>
<br><br>
<p>
<input type="checkbox" name="Mailing List" id="checkbox" onClick = "showMailingListForm()">
Please put me on your mailing list.
</p>
<div id = "mailingInformation">
<h3>Please fill out the form below to be put on the mailing list to recieve coupons and special offers</h3>
<p>Check the box to use address above
<input type = "checkbox" name = "checkForAddress" id = "checkAddress">
</p>
<p>First Name:
<input type = "text" name = "mailingName" id = "mailing">
</p>
<p>Last Name:
<input type = "text" name = "mailingLastName" id = "mailingLast">
</p>
<p>Mailing Address:
<input type = "text" name = "mailingAddress" id = "mailingAdd">
</p>
<p>Phone Number(Optional)
<input type = "text" name = "phoneNumber" id = "phone">
</p>
</div>
<p>
<input type="checkbox" name="More Info" id="checkbox2">
Send me more information about your products.</label>
</p>
<br><br>
<p>
<input type="hidden" name="hiddenField" id="hidden" value="application-id:US447">
</p>
<br><br>
<p>
<input type="submit" name="button" id="button" value="Submit">
<input type="reset" name="button2" id="button2" value="Reset">
</p>
<div>
</form>
<div id = "hiddenStuff">
<p>
<table border='a'>
<tr>
<th>Field Name</th>
<th>Value of Field</th>
</tr>
<?php echo $tableBody; ?>
</table>
<!--</p>
<p>Name: <?php echo $inName; ?></p>
<p>Email: <?php echo $inEmail; ?></p>
<p>Address: <?php echo $inAddress; ?></p>
<p>Reason: <?php echo $inReason; ?></p>
<p>Comments: <?php echo $inComments; ?></p>
<p>Mailing List: <?php echo $inMailBox; ?></p>
<p>Use Previous Address Given: <?php echo $inUseAddress; ?></p>
<p>First Name: <?php echo $inFirstName; ?></p>
<p>Last Name?: <?php echo $inLastName; ?></p>
<p>Mailing Address: <?php echo $inMailingAdd; ?></p>
<p>Phone Number: <?php echo $inPhoneNumber; ?></p>
<p>More Information: <?php echo $inMoreInfo; ?></p>-->
</div>
</body>
</html>
Some line of code have been commented out for the sake of experimenting. Thank you in for the help.
That's because of this:
<?php
$toEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Place email address where you wish to send the form data.
//Use your DMACC email address for testing.
//Example: $toEmail = "jhgullion#dmacc.edu";
$subject = "WDV341 Email Example"; //CHANGE within the quotes. Place your own message. For the assignment use "WDV101 Email Example"
$fromEmail = "robinjennings#nephilim42.com"; //CHANGE within the quotes. Use your DMACC email address for testing OR
//use your domain email address if you have Heartland-Webhosting as your provider.
//Example: $fromEmail = "contact#jhgullion.org";
// DO NOT CHANGE THE FOLLOWING LINES //
$emailBody = "Form Data\n\n "; //stores the content of the email
foreach($_POST as $key => $value) //Reads through all the name-value pairs. $key: field name $value: value from the form
{
$emailBody.= $key."=".$value."\n"; //Adds the name value pairs to the body of the email, each one on their own line
}
$headers = "From: $fromEmail" . "\r\n"; //Creates the From header with the appropriate address
if (mail($toEmail,$subject,$emailBody,$headers)) //puts pieces together and sends the email to your hosting account's smtp (email) server
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
You have to check if your form is submitted then the above code executes. So put the above code in:
if( isset($_REQUEST['form_element_index']) )
{
// Above code here
// Now the code executes when form is submitted
}
Its happening because you have't created a form and asked user to give input.What you have to do is create a form and then retreive the form values and upon submitting the form send the mail.It would definitely work....

php mail form on magento product page

I am trying to make a simple price match contact form on my product page in Magento. I have a separate php file but it doesn't seem to receive the commands from the view.phtml file.
this is the form code which is located inside /app/design/frontend/default/my_design/template/catalog/product/view.phtml
<div class="pricematcher">
<body class="body">
<div id="pricematch" style="display:none;">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="send_contact.php" id="form" method="post" name="form">
<img id="close" src="<?php echo $this->getSkinUrl(); ?>images/close.png" onclick="div_hide()"</img>
<h2 class="h2price">Price Match</h2>
<hr id="hrprice">
<input id="name" name="name" placeholder="Name" type="text">
<input id="email" name="email" placeholder="Email" type="text">
<input id="productname" name="productname" placeholder="<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' PART #: ');?><?php echo $_helper->productAttribute($_product, nl2br($_product->getSku()), 'sku') ?>" type="text" readonly>
<input id="competitor" name="competitor" placeholder="Competitor Product Link" type="text">
<textarea id="msg" name="msg" placeholder="Message"></textarea>
Submit
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<!-- Display Popup Button -->
</body>
</div>
<img id="popup" src="<?php echo $this->getSkinUrl(); ?>images/price-match.png" onclick="div_show()"</img>
this is the javascript which makes the form pop up and display
// Validating Empty Field
function check_empty() {
if (document.getElementById('name').value == "" || document.getElementById('email').value == "" || document.getElementById('msg').value == "") {
alert("Fill All Fields !");
} else {
document.getElementById('form').submit();
alert("Thank You for submitting a Price Match inquiry");
}
}
//Function to Hide Price Match
function div_hide(){
document.getElementById('pricematch').style.display = "none";
}
//Function To Display Price Match
function div_show() {
document.getElementById('pricematch').style.display = "block";
}
this is the php file that the form action should send to send_contact.php file located in the same directory as view.phtml
<?php
$subject = "Price Match";
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
// Enter Your email Adress
$to = "myemail#email.com";
$body = "$message, $competitor, $product";
$send_contact = mail($to,$subject,$body, "From: " . $mail_from);
//Check if message sent
if ($send_contact){
echo "we recieved";
}
else {
echo "error";
}
?>
Every thing works when I make this in a seperate folder on my server and execute outside of magento.
You should put send_contact.php at magento's root directory.
I think you can create an action in ProductController.php,for example,postEmailAction, then in the postEmailAction,you can get the data from the form:
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
, flow the code:
`
$mail = Mage::getModel('core/email');
$mail->setToName('YourStore Admin');
$mail->setToEmail($toEmail);
$mail->setBody($body);
$mail->setSubject('YourStore: New Product Review');
$mail->setFromEmail('donotreply#yourstore.com');
$mail->setFromName("YourStore");
$mail->setType('html');
try {
$mail->send();
}
catch (Exception $e) {
Mage::logException($e);
}
`
the action url will be the product controller + the action name;
Hope this will help you.

Form that allows multiple emails and sends to all

I have a form that will email the info to the email entered in the email field, but I want the user to be able to type in multipple emails in the one field and for the info to go to all of them. Can anyone help edit my code to allow this....
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Contact Form</title>
<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="website" content="http://web-kreation.com" />
<!-- the cascading style sheet-->
<link href="stylecontact.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="contentForm">
<!-- The contact form starts from here-->
<?php
$error = ''; // error message
$name = ''; // sender's name
$email = ''; // sender's email address
$subject = ''; // subject
$message = ''; // the message itself
$spamcheck = ''; // Spam check
if(isset($_POST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$spamcheck = $_POST['spamcheck'];
if(trim($name) == '')
{
$error = '<div class="errormsg">Please enter your name!</div>';
}
else if(trim($email) == '')
{
$error = '<div class="errormsg">Please enter your email address!</div>';
}
else if(!isEmail($email))
{
$error = '<div class="errormsg">You have enter an invalid e-mail address. Please, try again!</div>';
}
if(trim($subject) == '')
{
$error = '<div class="errormsg">Please enter a subject!</div>';
}
else if(trim($message) == '')
{
$error = '<div class="errormsg">Please enter your message!</div>';
}
else if(trim($spamcheck) == '')
{
$error = '<div class="errormsg">Please enter the number for Spam Check!</div>';
}
else if(trim($spamcheck) != '5')
{
$error = '<div class="errormsg">Spam Check: The number you entered is not correct! 2 + 3 = ???</div>';
}
if($error == '')
{
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}
// the email will be sent here
// make sure to change this to be your e-mail
$to = "jeengle#indiana.edu";
// the email subject
// '[Contact Form] :' will appear automatically in the subject.
// You can change it as you want
$subject = '[Contact Form] : ' . $subject;
// the mail message ( add any additional information if you want )
$msg = "From : $name \r\ne-Mail : $email \r\nSubject : $subject \r\n\n" . "Message : \r\n$message";
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
?>
<!-- Message sent! (change the text below as you wish)-->
<div style="text-align:center;">
<h1>Thank You</h1>
<p>Thanks, <b><?=$name;?></b>. Your input is important to us.</p>
</div>
<!--End Message Sent-->
<?php
}
}
if(!isset($_POST['send']) || $error != '')
{
?>
<center><h1>Contact Us</h1></center>
<!--Error Message-->
<?=$error;?>
<form method="post" name="contFrm" id="contFrm" action="">
<label><span class="required">*</span> Name:</label>
<input name="name" type="text" class="box" id="name" size="30" value="<?=$name;?>" />
<label><span class="required">*</span> Email: </label>
<input name="email" type="text" class="box" id="email" size="30" value="<?=$email;?>" />
<label><span class="required">*</span> Subject: </label>
<input name="subject" type="text" class="box" id="subject" size="30" value="<?=$subject;?>" />
<label><span class="required">*</span> Message: </label>
<textarea name="message" cols="35" rows="3" id="message"><?=$message;?></textarea>
<br>
<label><span class="required">*</span> Spam: <b>2 + 3=</b></label>
<input name="spamcheck" type="text" class="box" id="spamcheck" size="4" value="<?=$spamcheck;?>" /><br /><br />
<!-- Submit Button-->
<center><input name="send" type="submit" class="button" id="send" value="" /></center>
</form>
<!-- E-mail verification. Do not edit -->
<?php
}
function isEmail($email)
{
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));
}
?>
<!-- END CONTACT FORM -->
</div> <!-- /contentForm -->
</body>
</html>
If it is multiple recipients you are looking for, you can provide them to the mail() function using delimited $to parameter as described here: http://www.php.net/manual/en/function.mail.php#108340
Here's the text from the link to prevent rot:
Marc Parillo 18-Apr-2012 01:27
If you follow the suggested format for the $to field, you can list multiple addresses in a comma-delimited string with spaces.
The spaces could be an issue if you're experiencing a similar problem. I was unable to send an e-mail to multiple addresses using that format. It started working for me when I removed all of the spaces in the $to string.
Example:
<?php
$to = 'nobody#example.com,anotheruser#example.com,yetanotheruser#example.com'; // no spaces
mail($to, 'the subject', 'the message');
?>

Categories

Resources