I tried to show user input after they submit their form.
Here is the form looks like:
<form class="form-horizontal col-sm-12" name="enq" method="post" action="email/" >
<div class="form-group"><label>Name</label><input class="form-control required" name="name" placeholder="Your name" data-placement="top" data-trigger="manual" data-content="Must be at least 3 characters long, and must only contain letters." type="text"></div>
<div class="form-group"><label>Message</label><textarea class="form-control" name="message" placeholder="Your message here.." data-placement="top" data-trigger="manual"></textarea></div>
<div class="form-group"><label>E-Mail</label><input class="form-control email" name="email" placeholder="email#you.com (so that we can contact you)" data-placement="top" data-trigger="manual" data-content="Must be a valid e-mail address (user#gmail.com)" type="text"></div>
<div class="form-group"><label>Phone</label><input class="form-control phone" placeholder="999-999-9999" data-placement="top" data-trigger="manual" data-content="Must be a valid phone number (999-999-9999)" type="text"></div>
<div class="form-group"><input type="submit" class="btn btn-success pull-right" id="submit" name="submit"></input> <p class="help-block pull-left text-danger hide" id="form-error"> The form is not valid. </p></div>
</form>
Here is the PHP after the user submit:
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../success.php");
else
header("Location:../test.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
And here is success.php:
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$name."<br>";
echo "<strong>Email:</strong> ".$email."<br>";
echo "<strong>Message:</strong> ".$query."<br>";
I could receive what the user sent in my email, but the problem is with success.php, I tried to use the above code, but what I got is undefined index.
Is there a way to show the input values in the new page after submit?
Use session variables or you could alternatively send the data through the URL and use $_GET on the success page (I probably don't suggest this though).
PHP after submit:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
{
session_start();//Start the session
$_SESSION['name'] = $name; //Set name session
$_SESSION['email'] = $email; //Set email session
$_SESSION['query'] = $query; // Set query session
header("Location:../success.php");
}
else
{
header("Location:../test.php?msg=Error To send Email !");
}
}
?>
success.php
<?php
session_start();
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$_SESSION['name']."<br>";//Use the session variables
echo "<strong>Email:</strong> ".$_SESSION['email']."<br>";
echo "<strong>Message:</strong> ".$_SESSION['query']."<br>";
?>
It essentially saves the data into variables that will work whenever sessions are started on alternative pages and can be called using $_SESSION.
You are redirecting to another page so the post values are not passed to the success page. What you could do it put them temporairy in a session
Related
this is my html, my php, and ajax for a contact form. It works great except it post the relpys in a new browser tab. I have spent hours trying to correct it. Please help.
html-
<!-- form fields -->
<form action="assets/php/contact.php" method="post" name="contactform" id="contactform" class=" animated out" data-animation="fadeInUp" data-delay="0">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Name">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="subject" id="subject" placeholder="Subject">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" name="message" id="message" placeholder="Message..."></textarea>
</div>
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="form-group">
<input type="submit" name="submit" value="Send message" id="submit" class="btn btn-sm btn-primary">
</div>
<div id="alert"></div>
</form>
PHP-
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(trim($name) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You must enter your name.</p></div>';
exit();
} else if(trim($email) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter a valid email address.</p></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You have entered an invalid e-mail address, try again.</p></div>';
exit();
}
if(trim($message) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter your message.</p></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "your#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name ." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<div class='notification success clearfix'><p>Thank you <strong>$name</strong>, your message has been submitted to us.</p></div>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
JS-
/* ==============================================
Contact Form
=============================================== */
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#alert").slideUp(750,function() {
$('#alert').hide();
$('#submit')
.after('<img src="assets/images/ajax-loader.GIF" class="contactloader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
},
function(data){
document.getElementById('alert').innerHTML = data;
$('#alert').slideDown('slow');
$('#contactform img.contactloader').fadeOut('slow',function(){$(this).remove();});
$('#submit').removeAttr('disabled');
if(data.match('success') !== null) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
}
);
});
return false;
});
I want error or success messages to show on the contact.html page and not open a new browser tab.
Thank you advance for help restore my sanity.
Cheers
You just need to prevent the default form submit from firing, which will post the content to the URL in your form action.
$('#contactform').submit(function(event){
event.preventDefault();
...
});
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have problem with send email. When I send a form, I get a blank message in my inbox. It looks like this:
Mail:
New message from:
E-mail:
Topic:
Sent message:
The form has validation, it works correctly. The problem is that I don't know why messages come empty to my inbox.
Here is a php code:
$name = $_POST['name'];
$mail = $_POST['mail'];
$topic = $_POST['topic'];
$message = $_POST['message'];
$email_to = "example#qmail.com";
$email_subject = "You received a new message";
$email_body = "Mail: \r\n";
$email_body .= "New message from: " . $name . "\r\n";
$email_body .= "E-mail:" . $mail . "\r\n";
$email_body .= "Topic: " . $topic . "\r\n";
$email_body .= "Sent message: " . $message . "\r\n";
$success = mail($email_to, $email_subject, $email_body);
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=success-form\index.html\">";
}
else{
print "<script>console.log('error'); </script>";
}
?>
Form in HTML:
<form method="post" action="../form.php" >
<input name="name" type="text" placeholder="Name and Surname">
<label></label>
<input name="mail" type="email" placeholder="Email address">
<label></label>
<input name="topic" type="text" placeholder="Topic">
<label></label>
<textarea name="message" placeholder="Message..."></textarea>
<label></label>
<input type="submit" class="send-btn" value="Send">
</form>
Have you tried adding a few headers? For example:
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "FROM:".$email_from."\r\n"; // Variable to define
Then, call you mail command like this:
$success = mail($email_to, $email_subject, $email_body, $headers);
I am creating a contact form for my website and I am having slight problems. It works fine when not using location and I get an email but when using location I do not get an email when entering the form.
How can I redirect and get the email at the same time?
HTML:
<div class="contact-form">
<div class="contact-form-container">
<form novalidate action="index.php" method="POST">
<label id="label-0">Position</label>
<select name="position_form">
<option value="collaboration_partner">Samarbetspartner</option>
<option value="youth_organization">Ungdomsorginisation</option>
<option value="young_enterprise">Ung Företagsamhet</option>
<option value="work_group">Arbetsgrupp</option>
<option value="school">Skola</option>
<option value="volunteer_trainee">Volontär/Praktikant</option>
<option value="charity">Välgörenhet</option>
<option value="sponsor">Sponsor</option>
<option value="other">Annat</option>
</select>
<label id="label-1">Namn</label>
<input name="name" placeholder="Namn" type="text">
<label id="label-2">Email Adress</label>
<input name="email" type="text" placeholder="Email Adress">
<label id="label-3">Meddelande</label>
<textarea name="message" placeholder="Meddelande"></textarea>
<input id="submit" name="submit" type="submit" value="SKICKA">
</form>
</div>
</div>
PHP:
<?php
$to = "random#protonmail.com";
$subject = "Kontakta Oss - Senaste Meddelande";
$name = $_POST['name'];
$email = $_POST["email"];
$position_form = $_POST["position_form"];
$message = $_POST["message"];
$body = <<<EMAIL
Namn:
$name
Email:
$email
Position:
$position_form
Meddelande:
$message
EMAIL;
$header = "from: kontakt#example.com";
header('Location: http://example.com/redirecthere.php');
exit();
if($_POST){
mail($to, $subject, $body, $header);
}
?>
Try change your php file this way:
<?php
$to = "random#protonmail.com";
$subject = "Kontakta Oss - Senaste Meddelande";
$name = $_POST['name'];
$email = $_POST["email"];
$position_form = $_POST["position_form"];
$message = $_POST["message"];
$body = <<<EMAIL
Namn:
$name
Email:
$email
Position:
$position_form
Meddelande:
$message
EMAIL;
$header = "from: kontakt#example.com";
if($_POST){
mail($to, $subject, $body, $header);
header('Location: http://example.com/redirecthere.php');
exit();
}
?>
I hope this help you.
by the way I suggest you look for transactional email services like Mailgun, Sendgrid among others.
The mail function is called (in fact, it's never called) after the header('Location. Even if you remove the header it wouldn't send mail because there's an exit function called before you get the if.
Remove the exit and move the header to the end of the file
I'm trying to get my simple contact form to be functional. I want this form to either email me or record the contact data somewhere. I'm just now starting to learn PHP and Javascript -- so my knowledge is extremely limited.
The validation seems to be working (it will alert you if you don't put in a valid email, for example) -- but the form itself isn't being submitted anywhere.
When you enter information and click submit you'll get an ERROR 404 - Not Found (Then it references contact.php -- the php file I'm using) How can I start to troubleshoot this? Furthermore, if you have a clear, simple resource for learning about PHP and forms then I'd be more than happy to study more. I've searched (for a few hours) for decent tutorials but most don't provide clear explanations -- and just encourage you to copy and paste code.
<form role="form" id="contactform" form action="contact.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="subject" class="form-control" id="subject">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" rows="3"></textarea>
</div>
<button type="submit" class="btn">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</form>
---PHP---
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$EmailTo = "william#whatsauce.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .="Subject: ";
$Body .= $subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>
Use a name attribute in your input fields. Only then you will be able to capture them values in your $_POST as a valid index, not through ids.
After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.