php mail() sending mail before form is filled - javascript

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

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>

PHP/js Contact form not posting form data across

So I have a contact form on my website, which is partially working - The email is being sent to the intended email address, but the contents of the form are not included in the email. I do get the labels for the form inputs within the email, just not what the user inputs as their details.
I've examined and re-examined the variables and checked for typo's & syntax errors in the code but can't find any. PHP & js isn't my strong point so I'm hoping the kind & clever people here can point me in the right direction.
The HTML and js:
<form id="contact-form" name="contact-form" method="post" action="form-processing.php" style="float: right;">
<span id="sprytextfield1">
<label for="Name:">Name:</label>
<br />
<input name="Name" type="text" id="Name" tabindex="10" />
<span class="textfieldRequiredMsg">*</span></span>
<p><span id="sprytextfield2">
<label for="Email:">Email:</label>
<br />
<input type="text" name="Email" id="Email" tabindex="20"/>
<span class="textfieldInvalidFormatMsg">*</span></span>
</p>
<p><span id="sprytextfield3">
<label for="PhoneNumber">Phone Number:</label>
<br />
<input type="text" name="PhoneNumber" id="PhoneNumber" tabindex="30"/>
<span class="textfieldRequiredMsg">*</span></span>
<p><span id="sprytextfield4">
<label for="Message">Message:</label>
<br />
<textarea name="Message" cols="20" rows="10" id="Message" tabindex="40"></textarea>
<span class="textfieldRequiredMsg">*</span></span>
</p>
<p>
<input type="submit" name="Send" id="Send" value="Send" tabindex="50" />
</p>
</form>
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "Name");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "Email", {
isRequired: false
});
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "PhoneNumber", {
format: "phone_custom",
pattern: "07234567890",
validateOn: ["blur"]
});
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "Message");
</script>
The PHP code:
<?php
while (list($key, $val) = #each($_GET)) $GLOBALS[$key] = $val;
while (list($key, $val) = #each($_POST)) $GLOBALS[$key] = $val;
while (list($key, $val) = #each($_COOKIE)) $GLOBALS[$key] = $val;
while (list($key, $val) = #each($_FILES)) $GLOBALS[$key] = $val;
while (list($key, $val) = #each($_SESSION)) $GLOBALS[$key] = $val;
/* Subject and Email Variables */
$emailSubject = 'Website Contact Form';
$webMaster = 'jonnylovesspam#gmail.com';
/* Gathering Data Variables */
$nameField = $_POST['Name'];
$emailField = $_POST['Email'];
$PhoneNumberField = $_POST['PhoneNumber'];
$messageField = $_POST['Message'];
$body = <<<EOD
<br><hr><br>
Name: $nameField <br>
Email: $emailField <br>
Phone Numbers: $PhoneNumberField <br>
Message: $messageField <br>
EOD;
$headers = "From: $email\r\n";
$headers = "Content-type: text/html\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
/* Results Rendered as HTML */
$theResults = <<<EOD
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><br />
<meta HTTP-EQUIV="REFRESH" content="0; url=contact-message-sent">
<style type="text/css">
<!--
body {
background-color: #fffff;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
font-style: normal;
line-height: normal;
font-weight: normal;
color: #000000;
text-decoration: none;
}
-->
</style>
</head>
<div align="left">
Redirecting you...</div>
</body>
</html>
EOD;
echo "$theResults";
?>
You can see the form in action here: http://www.clearpandb.co.uk/contact
Thank you in advance for any pointers or help you can offer.
Without your javascript it's working ?
For my form i use HTML5 input type:
HTML5 added several new input types:
color
date
datetime
datetime-local
email
month
number
range
search
tel
time
url
Best regards,
Florent.

PHP session variable's value in 1st page not updating to value of session variable in 2nd page after 2nd GET request

I am using session variables in PHP. I am making an ajax request from modifyDetails.php to another php file named getDetails.php using :
xmlhttp.open("GET", "getDetails.php?val=" + str, true);
I am trying to change the values of form fields based on the selection made in dropdown list. I am getting it correct when I make a selection for the first time
but when i make a different selection now , the values are still the same.
I have checked the values of session variable $_SESSION['Member_details'] in getDetails.php and it's values are perfectly fine but the session variable in
modifyDetails.php is not updating it's value.
"modifyDetails.php"
<?php
session_start();
$fid = $_SESSION['fid_value'];
$get_Member_details = $_SESSION['Member_details'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Modify Details</title>
<script src="/prj/jquery.min.js"></script>
<script>
function fillData(str)
{
$(document).ready(function()
{
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("kk").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getDetails.php?val=" + str, true);
xmlhttp.send();
//window.alert(str);
var jage= "<?php echo $get_Member_details['age'];?> ";
var jsex= "<?php echo $get_Member_details['sex'];?> ";
var jdob= "<?php echo $get_Member_details['dob'];?> ";
//alert(jdob);
var jrelation = "<?php echo $get_Member_details['Relationship'];?> ";
var jcontact = "<?php echo $get_Member_details['contact'];?> ";
var jaddress = "<?php echo $get_Member_details['address'];?> ";
var jpin = "<?php echo $get_Member_details['pin'];?> ";
document.getElementById("Age").value = jage;
//document.getElementById("Sex").value = jsex;
document.getElementById("Dob").value = jdob;
document.getElementById("Rel").value = jrelation;
document.getElementById("Contact").value = jcontact;
document.getElementById("Address").value = jaddress;
document.getElementById("Pin").value = jpin;
});
}
</script>
<style>
body{
background-color:lightgrey;
}
#button {
background-color: green;
border: none;
color: white;
padding: 8px 14px;
text-align: center;
text-decoration: none;
font-size: 17px;
margin: 2px 4px;
cursor: pointer;
}
table { padding:2px 6px;}
</style>
</head>
<body>
<h1>Customer Form </h1>
<h3>Please fill in the details below:</h3>
<form action="modified.php" method="post">
<table style="width:24%;">
<tr><td>Family ID:</td><td><input type="text" name="fid" value="<?php echo "$fid";?>" readonly /></td></tr><tr></tr>
<tr><td>Name:</td>
<td>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('project');
$sql_query = "SELECT name FROM family WHERE fid=$fid";
$records = mysql_query($sql_query);
echo"<select name='member_name' onchange='fillData(this.value)'>";
while( $family_member = mysql_fetch_array($records) )
{
echo "<option value='".$family_member['name']."' >".$family_member['name']."</option>";
}
echo "</select></td></tr>";
?>
<div id="kk">
</div>
<tr><td>Age:</td><td><input id="Age" type="text" name="age" required /></td></tr><tr></tr>
<tr><td>Sex:</td><td><input id="Sex" type="radio" name="sex" value="Male" required />Male
<input id="Sex" type="radio" name="sex" value="Female" required/>Female</td></tr><tr></tr>
<tr><td>Date of Birth:</td><td><input id="Dob" type="text" name="dob" required /></td></tr><tr></tr>
<tr><td>Relationship:</td><td><input id="Rel" type="text" name="relation" list="relations" required>
<datalist id="relations">
<option value="Son">Son</option>
<option value="Daughter">Daughter</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="GrandMother">GrandMother</option>
<option value="GrandFather">GrandFather</option></td></tr><tr></tr>
</datalist></td></tr>
<tr><td>Contact Number:</td><td><input id="Contact" type="text" name="contact" required /></td></tr><tr></tr>
<tr><td>Address:</td><td><input id="Address" type="text" name="address" required /></td></tr><tr></tr>
<tr><td>Pincode:</td><td><input id="Pin" type="text" name="pin" required /></td></tr><tr></tr>
</table> <br>
<input id="button" type="submit" value="Submit"/>
</form>
<br><br><br>
<h4>Back to Search Page</h4>
</body>
"getDetails.php"
<?php
session_start();
$fid =$_SESSION['fid_value'];
?>
<?php
$name=$_GET['val'];
echo $name;
mysql_connect('localhost', 'root', '');
mysql_select_db('project');
$sql_query = "SELECT * FROM family WHERE fid=$fid AND name='$name'";
$records = mysql_query($sql_query);
$_SESSION['Member_details'] = mysql_fetch_array($records);
$hold = $_SESSION['Member_details'];
//echo $hold['dob'];
//echo $hold['contact'];
?>
Ajax call happens after page load, you JS is getting rendered when the session is in State 'A'.
Once you make your Ajax call, it`s in sate 'B', but at that point call to Session has already been made and the initial view is already rendered.
So, to fix the situation you should pass variables that are changing through Ajax reposne with JSON for example.

how to validate my form using javascript [closed]

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.

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(); ?>

Categories

Resources