PHP/js Contact form not posting form data across - javascript

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.

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>

comment from comment box is overriding, not posting [duplicate]

This question already has answers here:
Create or write/append in text file
(7 answers)
Closed 5 years ago.
when I hit the post button, comment is posting on the page. If I hit it again, it overriding the previous comment. can someone please clarify this? And I'm running java script to display the date. It is showing all the time without any comments also. How can I modify that too?
Thanks in advance!
<h3 id="reply-title" class="comment-reply-title">Leave a Reply </h3>
<form action="" method="post">
<p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
<p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" aria-required="true" required="required"></textarea></p>
<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" aria-required="true" required="required"></p>
<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="email" value="" size="30" maxlength="100" aria-describedby="email-notes" aria-required="true" required="required"></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"></p>
<div>
<?php
if($_POST) {
$name = $_POST['author'];
$comment = $_POST['comment'];
$email = $_POST['email'];
#echo $name . $comment . $email;
$handle = fopen("comments/get-more-twitter-followers.html", "a");
fwrite($handle, "\n".$name."\n".$comment."\n". $email. "\n");
fclose($handle);
}
?>
<?php
if($_POST) {
$email = $_POST['email'];
$useremail = fopen("useremail.html", "a");
fwrite($useremail, "\n".$email. "\n");
fclose($useremail);
}
?>
</div>
<div>
<div>
<p><strong><h4><u>Comments:</u></h4></strong></p>
</div>
<div>
<div>
<strong><?php
$name = $_POST['author'];
echo $name; ?> </strong> <small><script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write("/")
document.write(d.getMonth() + 1)
document.write("/")
document.write(d.getFullYear())
</script>
</small>
</div>
<div>
<p>
<?php
$comment = $_POST['comment'];
echo "\n".$comment."\n"."<hr>";
?>
</p>
</div>
</div>
</div>
Whay do you mean with; 'Your email address will not be published.' You write all 'mail addresses' to a plaintext file for crying out loud. DONT PUT THIS ONLINE.
You're not reading the file back to paint the comments, you are just using the POST data that came in:
<div>
<strong><?php
$name = $_POST['author'];
echo $name; ?> </strong> <small><script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write("/")
document.write(d.getMonth() + 1)
document.write("/")
document.write(d.getFullYear())
</script>
</small>
</div>
<div>
<p><?php
$comment = $_POST['comment'];
echo "\n".$comment."\n"."<hr>";
?></p></div>
</div></div>
</div>
$_POST in PHP refers to the body of the POST request that the script is responding to.
You need to replace that with functionality that does three things:
Reads from the file.
Splits the records into different entries with an author and comment.
Iterates over those entries and paints a separate div for each record.
Another gotcha: Your code is printing the current date as the date of the comment. If you are not storing the date of the comments, you probably shouldn't show the date.
<?php
$comment = $_POST['comment'];
$name = $_POST['author'];
$data_post->name = $name;
$data_post->comment = $comment;
if(isset($name, $comment)){
header('Content-type: application/json');
echo(json_encode($data_post));
return;
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$("document").ready(function(){
$("#comment").on("submit", function(e){
var comment = $('#comment');
e.preventDefault();
$.ajax({
method: "POST",
url: "index.php", // your php file name
data: comment.serialize(),
success: function (data) {
var d = new Date();
var data_comment = "<div><small>"+d.getDate()+"/"+(d.getMonth() + 1)+"/"+d.getFullYear()+"</small></div><strong>"+data.name+"</strong><p>"+data.comment+"</p>"
$("#list_comment").append(data_comment);
comment[0].reset();
console.log(data.name);
},
error: function (data) {
},
})
});
});
</script>
</head>
<body>
<h3 id="reply-title" class="comment-reply-title">Leave a Reply </h3>
<form action="" method="post" id="comment">
<p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
<p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" aria-required="true" required="required"></textarea></p>
<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" aria-required="true" required="required"></p>
<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="email" value="" size="30" maxlength="100" aria-describedby="email-notes" aria-required="true" required="required"></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"></p>
</form>
<div>
<div>
<p><strong><h4><u>Comments:</u></h4></strong></p>
</div>
<div id="list_comment">
<div>
</div>
</body>
</html>
don't forget to change url in ajax post with your php filename (line 26)

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 and HTML form mail send with javascript alert not working [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have very limited knowledge. I tried my best to understand. I want to send mail from a contact form, upon success show an alert message and remain on the same page. the mail is not sending and seems likeI have some bugs in the code. kindly help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6">
<input name="email" type=“text” class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if ($_POST['send']) {
$ToEmail = 'info#autonomousdata.com';
$EmailSubject = $_POST['subject'];
$mailheader = "From: ".$_POST['email']."\r\n";
$mailheader .= "Reply-To: ".$_POST['email']."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n" .
"X-Mailer: PHP/" . phpversion();
$MESSAGE_BODY = "Name: ".$_POST['name']."\n";
$MESSAGE_BODY .= "Email: ".$_POST['email']."\n";
$MESSAGE_BODY .= "Comment: ".$_POST['message']."";
if(mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)!==true) {
?>
<script type='text/javascript'> alert('failed to send the mail'); </script>
<?php
die('Fail to send');
} else{
?>
<script type='text/javascript'>alert('Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.');
</script>
<?php
}
}
?>
The HTML form had dubious quotation marks around the type='text' and I modified the php to add some rudimentary checking of variables and also sanitisation ~ hope it will help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='failed to send the mail';
break;
}
echo "<script type='text/javascript'>alert('{$msg}');</script>";
}
?>
The test page, in it's entirety, that I set up to test the basic functionality of the script. As this was all run locally I cannot confirm whether the email would be sent - it looks correct however.
<?php
?>
<!doctype html>
<html>
<head>
<title>Basic Contact Form - investigating email send failure.</title>
<script type='text/javascript' charset='utf-8'></script>
<style type='text/css' charset='utf-8'>
form{
width:50%;
}
form,output,input[type='text'],textarea,input[type='button'],input[type='submit']{
display:block;
box-sizing:border-box;
padding:0.5rem;
margin:0.5rem;
}
output{
color:red;
}
input[type='text'],textarea{
width:60%;
}
</style>
</head>
<body>
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
<output id='msgs'></output>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
if( !$to or !$name or !$subject or !$message or !$email ){
echo "Error: one or more required variables are not available.";
} else {
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='Failed to send the mail';
break;
}
/* Let the user know the status of the form submission somehow */
echo "
<script type='text/javascript'>
document.getElementById('msgs').innerHTML='{$msg}';
/*
alert('{$msg}');
*/
</script>";
}
}
?>
</body>
</html>

How to get success message after submit

Recently, I’ve been working with a lot of form confirmations. I’ve been thinking about the best way on how to approach these. Many forms redirect users either to a separate page displaying a thank you/confirmation message
i want to show mgs in same page . I have tried below code but i am not getting sucess mgs on same page. it redirect to contriler.php page
javascript file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("#Button1").click(function(event){
            $(".message").show();
            $(".message").fadeOut(2500);
        });
    });
</script>
html file
<div class="w-form">
<form method="POST" name="contactform" action="contact-form-handler.php" class="myform form-tablet" id="email-form" data-name="Email Form">
<select class="w-select form-select-field" id="Selection" name="Selection" required="required" data-name="Selection">
<option value="start project">Start Project</option>
<option value="work with us">Work with us</option>
<option value="just say yello">Just say hello</option>
</select>
<label class="labelfield" for="Name-3">*your Name:</label>
<input class="w-input textfield" id="Name-3" type="text" name="Name" data-name="Name" required="required">
<label class="labelfield" for="Email-3">*Your e-mail address</label>
<input class="w-input textfield" id="Email-3" type="email" name="Email" data-name="Email" required="required">
<label class="labelfield" for="Web">Your Website</label>
<input class="w-input textfield" id="Web" type="text" name="Web" data-name="Web">
<label class="labelfield" for="Message">Your Message to Us</label>
<textarea class="w-input textfield comment" id="Message" name="Message" data-name="Message"></textarea>
<input id="Button1" class="w-button submit-button" type="submit" value="Submit" data-wait="Please wait...">
</form>
<div class="message">Your update was successful.</div>
controler.php file
<?php
$errors = '';
$myemail = 'omprakash.k#fuegosys.com ';//<-----Put Your email address here.
$Selection=($_POST['Selection']);
$name=($_POST['Name']);
$email_address=($_POST['Email']);
$Web=($_POST['Web']);
$message=($_POST['Web']);
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
"$myemail /n $Selection /n $name /n $email_address/n $Web/n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: index.html#contact');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
My Problem is it not rederting tohome page with sucess mgs
$show_message= FALSE; // at the top of page
$message = "";
if($show_message= TRUE){
echo $message;
}
if(isset($_POST['sub'])){
//Php code goes here
$show_message = TRUE;
}
<input type ="submit" name="sub" />

Categories

Resources