how to validate my form using javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i want to validate my form using javascript .before the form submission,i want the server to display the error (if any)below the field input..how can i do dis in this code using external javascript file??
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
.label_text {
float: left;
width: 44%;
text-align:right;
font-weight:bold;
color:purple;
}
.register1{
text-align:center;}
.header_tag{text-align:center;
font-weight:bold;
color:green;}
.header_tag1{ margin:10px;
float:left;
text-align:center;
font-weight:bold;
color:green}
.register_section{border:1px solid black;
text-align:center;
padding:20px;
margin-left:30%;
margin-right:30%;
float:none;
height:350px;
}
.input{ text-align:left;
float:left;
border:2px solid black;
}
.gender{float:left;}
.register{ float:left;
text-align:center;
color:green;
font-weight:bold;
padding:10px;
margin-left:36%;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $passwordErr = $password2Err = $emailErr = $genderErr = "";
$name = $password = $confirmpassword = $email = $gender = $description = "";
$result="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = "";
$password = "";
$hostname = "";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select test");
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["confirmpassword"])) {
$password2Err = "Confirm Password";
} else {
$password = test_input($_POST["confirmpassword"]);
}
if ($_POST['password']!= $_POST['confirmpassword'])
{
echo("Oops! Password did not match! Try again. ");
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["description"])) {
$comment = "";
} else {
$comment = test_input($_POST["description"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($genderErr))
{if (empty($emailErr)){
if (empty($password2Err)){
if (empty($passwordErr)){
if (empty($nameErr)){
$result=mysql_query("SELECT * FROM person WHERE username ='$name' AND password='$password'AND Email='$email'");
if (mysql_num_rows($result)==0 )
{ // IF no previous user is using this username.
$result1=mysql_query("INSERT INTO person(username,password,Email,Gender) VALUES ( '$name', '$password','$email','$gender')");
{ if($result1)
////If the Insert Query was successfull.
// Send an email
// Finish the page:
{
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' </div>';
}
else
{ // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
}
// The username is not available.
else
{ echo '<div class="errormsgbox" >That username has already been registered.</div>';
}
}
}
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="register1">
<h2 class="header_tag">REGISTER HERE</h2>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="register_section">
<div class="label_text">
Name:<span class="error">* </div>
<div class="input">
<input type="text" name="name"><br> </div>
<span class="error"><?php echo $nameErr;?></span>
<br><br>
<div class="label_text">
Password:<span class="error">* </div>
<div class="input">
<input type="text" name="password"><br> </div>
<span class="error"><?php echo $passwordErr;?></span>
<br><br>
<div class="label_text">
Confirm Password:<span class="error">* </div>
<div class="input">
<input type="text" name="confirmpassword"><br> </div>
<span class="error"><?php echo $password2Err;?></span>
<br><br>
<div class="label_text">
E-mail:<span class="error">* </div>
<div class="input">
<input type="text" name="email"><br></div>
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<div class="label_text">
Description: </div>
<div class="input">
<textarea name="description" rows="5" cols="22"></textarea> </div>
<br><br>
<div class="label_text">
Gender:<span class="error">* </div>
<div class="gender">
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
</div>
<span class="error"><?php echo $genderErr;?></span>
<br><br><br>
<div class="register">
<input type="submit" name="submit" value="REGISTER">
<br>
<h3 class="header_tag1">"Back to Login
</div>
</div>
</div>
</form>
</body>
</html>

What you are trying to do is properly called client-side validation.
The easiest way to do this would be to use a third-party library, such as FormValidation.
For example, to validate your email field, you could do something like:
<form method="post" id="register_user" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
...
<input type="text" name="email" data-fv-emailaddress="true" data-fv-emailaddress-message="The value is not a valid email address" />
...
</form>
<script>
$('#register_user').submit(function() {
$('#register_user').formValidation();
});
</script>
Of course, you'll need to make sure to include the necessary CSS and JS libraries for jQuery, FormValidation, and a suitable content framework (such as Bootstrap).
For the record, if you're just looking for a basic user management script, I would strongly suggest that you avoid reinventing the wheel. Take an existing script, for example UserFrosting, and modify it to suit your needs.

Related

Need help on css display state using localStorage and jQuery

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>

Show a div after the form is submitted (or after pressing the "Send" button)

My task is to make a div visible after submitting a form. The problem is: after submitting the form, the div appears for 0.5 sec, then it disappears again.
This is the relevant code part. I want to show the div with id="data".
<form action="" method="post" onsubmit="show_div()">
<div class="request">
<center>
<img id="logo" src="/img/n1_red.png" alt="">
<h1 id="t_request" class="item">Account Name</h1>
<br/>
<input type="text" id="request" name="Request" value="<?php echo $cloud; ?>" class="item"><br/>
<input type="submit" class="bttn" class="item" onclick="show_div()" value="Send" /><br/>
</center>
</div>
<div id="data" style="display:none">
<h2 id="t_mail">Mail</h2>
<p class="result"><?php echo $Email; ?></p>
<h2 id="t_password">Password</h2>
<input type="checkbox" id="pass_visibility" onclick="unhide_password()" value="Unhide pass"/>
<label for="pass_visibility" id="pass_visibility_label">(Unhide pass)</label>
<p class="pass_result" id="text_hidden_pass">Password is hidden.</p>
<p class="result" id="text_pass" style="display:none"><?php echo $Password; ?></p>
<h2 id="t_total_gb">Total GB</h2>
<p class="result"><?php echo $Total_GB; ?></p>
<h2 id="t_gb_used">Used GB</h2>
<p class="result"><?php echo $GB_Used; ?></p>
<h2 id="t_about">About</h2>
<p class="result"><?php echo $About; ?></p>
<h2 id="t_key">KEY</h2>
<p class="result"><?php echo $Decryption; ?></p>
<h2 id="t_authy">Authy</h2>
<p class="result"><?php echo $Authy; ?></p>
<h2 id="t_nr_acc">Acc name</h2>
<p class="result"><?php echo $Name; ?></p>
</div>
</form>
and this is the JavaScript code:
var div = document.getElementById("data");
function show_div() {
div.style.display = "block";
}
I tried to do this in 2 different methods:
First one was to add onclick="show_div() to the submit button.
<input type="submit" class="bttn" class="item" onclick="show_div()" value="Send" /><br/>
Then I added onsubmit="show_div()" to the submit form.
<form action="" method="post" onsubmit="show_div()">
As I said, with this method (after submitting the form/clicking the button) the result is not as expected. The div appears for 0.5 sec, then it disappears again.
Not sure if you need, but here is the CSS for id="data":
#data {
border-top: dashed 3px rebeccapurple;
border-left: dashed 3px rebeccapurple;
padding-left: 20px;
display: block;
}
And here the PHP code:
$cloud = "";
$Email = "";
$Password = "";
$Name = "";
$Total_GB = "";
$GB_Used = "";
$About = "";
$Decryption = "";
$Authy = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$username = "root";
$password = "";
$db = "xxx";
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $con);
$cloud = $_POST["Request"];
// Query
$query = "SELECT * FROM Clouds WHERE Name = '$cloud' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
if ($result >= 1) {
while($row = mysql_fetch_assoc($result)) {
$Email = $row['Email'];
$Password = $row['Password'];
$Name = $row['Name'];
$Total_GB = $row['Total_GB'];
$GB_Used = $row['GB_Used'];
$About = $row['About'];
$Decryption = $row['Decryption'];
$Authy = $row['Authy'];
}
} else {
//$error_not_found = "Account not found!";
}
}
I am missing something? Any advice for me? Thanks
Another Stack Overflow question:
I checked everything. I followed her tips too. No result. Well... The same result
This is a snippet you may use. It is not possible to show a div and send the form together, see the comment of esque above.
<form id="form1" action="..." method="post">
<!-- here your form fileds -->
</form>
// true = show div --- false = send form
var showDiv = true;
// form id selector
var myForm = document.querySelector("#form1");
// bind submit event to form
myForm.addEventListener("submit", function(event) {
if (showDiv == false) {
console.log('send form');
return;
}
event.preventDefault();
console.log('Show div, form not send');
var div = document.getElementById("data");
div.style.display = "block";
});

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....

Clear input with submit button

Switching over from C# to PHP for a bit and not seeing what I am doing wrong here.
What I am wanting to to is when I click the submit button - I want the email sent (like it is doing) but then I want the input text fields to clear out the old text the user had previously input.
The one way I had it figured out would clear my test before it was actually submitted, which didn't help me very much.
Any input on how to do this?
<?php
/*
* Template Name: Contact
* Description: Contact Us
*/
get_header();
?>
<div class="container">
<div class="section group">
<div class="col span_2_of_2">
<h1> Contact Us <h1>
<p style="font-size:16px"> Radiology Services LLC is located on the east side of Evansville, IN off the Robert D. Orr Highway.</p>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3146.027108890167!2d- 87.45272299999999!3d37.953153!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x170f5925d75e6135!2s Radiology+Services+LLC!5e0!3m2!1sen!2sus!4v1404175203674" width="100%" height="350px" frameborder="0" style="border:0"></iframe>
</div>
<div class="col span_1_of_2" style="padding-left:40px;>
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = 'aje#gmail.com';
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent);
else my_contact_form_generate_response("error", $message_unsent);
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="entry-content">
<?php the_content(); ?>
<style type="text/css">
.error{
padding: 5px 9px;
border: 1px solid red;
color: red;
border-radius: 3px;
}
.success{
padding: 5px 9px;
border: 1px solid green;
color: green;
border-radius: 3px;
}
form span{
color: red;
}
.subBtn{
width:100%;
border-radius: 0px;
background-color:#5bb75b;
color:#FFFFFF;
}
.subBtn:hover{
background-color:#408140;
}
.m{
width:100%;
border-radius: 0px;
}
</style>
<script language="javascript">
fromreset()
{
myform.reset();
document.myform.[textbox Id] = " ";
}
</script>
<form name="myform" id="myform"action="<?php the_permalink(); ?>" method="post">
<label for="name" class="m">Name: <span>*</span> <br>
<input type="text" class="m" id="name" name="message_name" value="<?php echo esc_attr($_POST['message_name']); ?>">
</label>
<label for="message_email" class="m">Email: <span>*</span> <br>
<input type="text" class="m" id="email" name="message_email" value="<?php echo esc_attr($_POST['message_email']); ?>">
</label>
<label for="message_text" class="m" id="mu">Message: <span>*</span> <br>
<textarea type="text" class="m" id="textm" name="message_text"><?php echo esc_textarea($_POST['message_text']); ?></textarea>
</label>
<label for="message_human" class="m">Human Verification: <span>*</span> <br>
<input type="text" class="m" name="message_human"> + 3 = 5
</label>
<input type="hidden" name="submitted" value="1" class="m">
<input type="hidden" name="submitted" value="1" style="width:100%">
<input type="submit" value="submit" class="subBtn" onclick="formreset();">
<?php echo $response; ?>
</form>
</div>
</div>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div>
<?php get_footer(); ?>

Contact form does not validate on an iphone

The following contact form is not validating when submitting from an iphone...
It can be previewed here: loaistudio.com/contact
When I tried to submit the form without felling the fields, it opened a new blank page showing number 1 only on the top left side "which is not suppose to do at all" and actually sent the form empty... It does not do that on desktop.
I played around with the code trying to find the issue but no idea where is the problem! please help.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "EMAIL GOES HERE";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website</title>
</head>
<body>
<div class="wrapper" id="contactPage">
<div class="content">
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form action="contact.php" id="contactForm" method="post" name="contactForm">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" placeholder="Enter Name" required="" type="text">
</div>
<div class="email">
<p>Email Address</p>
<input name="email" placeholder="Enter Email" required="" type="email">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" required=""></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
</body>
</html>
you are adding jquery at the end of the html but you are using jquery before that, so javascript breaks with Uncaught ReferenceError: $ is not defined.
try moving this line to header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
This is code You have added AND THEN INCLUDED JQUERY, :) SO USE JQUERY IN HEADER !

Categories

Resources