I can't get this HTML form to post the data to PHP. The mail comes through ok, and has the titles (i.e. First Name: or Last Name:) but the actual data submitted is blank. What could be wrong with it?
HTML FORM DATA:
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<a name="contact" class="more scrolly"></a>
<h2>We'll call you back!</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="first" class="form-control" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" name="last" class="form-control" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" required placeholder="Phone Number">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required placeholder="Email">
</div>
<div class="form-group">
<select input type="text" name="debt" class="form-control">
<option value="Debt_Level">Debt Level</option>
<option value="-">-</option>
<option value="3000-5000">£3000-£5000</option>
<option value="6000-1000">£6000-£10,000</option>
<option value="11000+">£11,000+</option>
</select>
</div>
<div class="form-group">
<input type="occupancy" name="occupancy" class="form-control" required placeholder="Occupancy">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
</div>
PHP FORM DATA:
<?php
// if(!isset($_POST['submit']))
if(!empty($_POST['first']) && !empty($_POST['last']) && !empty($_POST['phone']) && !empty($_POST['email']) && !empty($_POST['purpose']) && !empty($_POST['amount']) && !empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$debt = $_POST['debt'] ;
$occupancy = $_POST['occupancy'] ;
$email_from = 'trustmoney.co.uk';//<== update the email address
$email_subject = "Landing Page App'";
$email_body = "You have received a new application request from: $email \n".
"First Name:” $first “\n".
"Last Name: “$last “\n".
"Telephone: “$phone “\n".
"Email: “$email “\n".
"Debt Amount:”$debt “\n".
"Occupancy: “$occupancy “\n".
"\n".
"\n".
"Sent from trustmoney.co.uk to: “\n".
$to = "matt.mckracken#trustmoney.co.uk \n";//<== update the email address
$headers = "From: $email_from";
//$headers .= "Reply-To: $email ";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
?>
The logic of you PHP doesn't really make sense. As #Epodax has pointed out you are checking if the input value aren't empty, then outputting an error saying they are but the email code is not even inside the IF function.
Your strings where you output the data aren't concatenated properly either.
$email_body = echo "You have received a new application request from:".$email."\n".
"First Name:".$first."\n".
"Last Name: "$last "\n". REST_OF_CODE_HERE
A better structure for managing your form validation would be breaking it down for the user and returning them to the form with appropriate errors.
Something like
$_SESSION['POST_VARS'] = $_POST;
$errors = 0;
if(empty($_POST['first'])) {
$_SESSION['errorFirst'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
if(empty($_POST['last'])) {
$_SESSION['errorLast'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
Then count the errors
if($errors == 0) {
// Your Submit Email Code
} else {
require( "YOUR_FORM_HERE.php" );
}
Then you can just output the correct session variable in your form with the appropriate error displayed
if(isset($_SESSION['errorFirst'])) { echo "<div class=\"validateError\">" . $_SESSION['errorFirst'] . "</div>"; unset($_SESSION['errorFirst']); };
Also you can return the users original values to the form so they don't have to start from scratch.
<input type="text" name="first" class="form-control" value="<?php if(!empty($_SESSION['POST_VARS']['first'])) { echo $_SESSION['POST_VARS']['first']; }; ?>"/>
Using this method you'll be able to output all the errors in your form to you users.
There is an error in your logic implementation.You Should use an || instead of && as follows
if(empty($_POST['first']) || empty($_POST['last']) || empty($_POST['phone']) || empty($_POST['email']) || empty($_POST['purpose']) || empty($_POST['amount']) || empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
Is there an efficient way to pass variables from one page to another after form submission? I'm struggling to maintain the variables that are submitting on the form page to display them on the confirmation page after being redirected on submission.
Could it be the way i'm 'storing' the data with $_POST? Should I be using sessions? If I should how would I go about storing the $_POST in $_SESSION and being able to call it in the email template as a $variable-name format? Is using header(); to redirect inefficient in this manner and maybe redirecting via ajax? Not sure how I would approach that if so.
Form:
<form id="pricing-form-inquiry" action="<?php echo get_stylesheet_directory_uri(); ?>/pricing-form/form-handler.php" method="POST" role="form">
<div class="pricing-modal" id="modal1" data-animation="slideInOutLeft">
<div class="modal-dial">
<header class="modal-head">
<a class="close-modal" aria-label="close modal" data-close></a>
</header>
<section class="modal-body">
<div class="row">
<div class="col">
<input type="text" class="" placeholder="First Name" name="first-name" required data-error="First Name is required.">
</div>
<div class="col">
<input type="text" class="" placeholder="Last Name" name="last-name" required data-error="Last Name is required.">
</div>
</div>
<input type="email" class="" placeholder="Email Address" name="email" required data-error="Email Address is required.">
<input type="text" class="" placeholder="Company" name="company" id="company">
<input type="text" class="" placeholder="Phone Number" name="phone" id="phone">
<div class="row">
<div class="col text-center"></div>
</div>
</section>
<footer class="modal-foot">
<input type="submit" class="pricing-form-submit" value="Calculate" name="submit">
</footer>
</div>
</div>
</form>
form-handler.php
if(isset($_POST['submit'])) {
$first_name = filter_var($_POST['first-name'], FILTER_SANITIZE_STRING);
$last_name = filter_var($_POST['last-name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$company = filter_var($_POST['company'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$to = "email#email.com"; // Email Address to send lead to
$subject = "Subject Goes Here!"; // Subject of generated lead email
// HTML Message Starts here
$message = "<html><body><table style='width:600px;'><tbody>";
$message = "<tr><td style='width:150px'><strong>Name: </strong></td><td style='width:400px'>$first_name $last_name </td></tr>";
$message = "<tr><td style='width:150px'><strong>Email Address: </strong></td><td style='width:400px'>$email</td></tr>";
$message = "<tr><td style='width:150px'><strong>Company Name: </strong></td><td style='width:400px'>$company</td></tr>";
$message = "<tr><td style='width:150px'><strong>Phone Number: </strong></td><td style='width:400px'>$phone</td></tr>";
$message = "</tbody></table></body></html>";
// HTML Message Ends here
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: Company <from#email.com>' . "\r\n"; // User will get an email from this email address
// $headers .= 'Cc: from#email.com' . "\r\n"; // If you want add cc
if(mail($to,$subject,$message,$headers)){
// Message if mail has been sent
echo "<script>
alert('Mail has been sent Successfully.');
</script>";
header("Location: /pricing-confirm/");
} else {
// Message if mail has been not sent
echo "<script>
alert('EMAIL FAILED');
</script>";
}
}
To pass your variables onto the pricing-confirm page, you could pass the variables in your header() function like so
header("Location: /pricing-confirm.php?name=" . $first_name);
Once on your pricing-confirm.php page, you can grab the variables from the query string
if(isset($_GET['name']) {
$name = $_GET['name'];
}
If you want to pass multiple variables at once, you can either use & in the query string, or use urldecode with an array like this
$arr = [
"firstname" => $first_name,
"lasttname" => $last_name,
]
header("Location: /pricing-confirm.php?userdetails=" . urlencode(serialize($arr)));
If you have used serialize, you can get the values in the array like this
$queryArr = unserialize(urldecode($_GET['userdetails']));
you can then access them with their array key, like so
if(isset($_GET['userdetails']) {
$arr = $_GET['userdetails'];
if(isset($arr['firstname']) {
$firstName = $arr['firstname'];
}
}
Im trying to build a simple contact form for a Wordpress site. I want it to send an email and reload the contact page it was sent from with an error/success message.
I have installed WP mail SMTP and it sends the test email.
Now to the problems. I have a form in html that I want to use. This form has been put in a custom template.
The php is borrowed from guides I have found online and I have used several of them. None of them work for me. When I hit the submit button the page loads the base template (not the custom template that I'm using for the form page) and no mail is sent. I want it to load the same page but with an error/success div telling me what happened. If I run the php before pressing submit it gives me the error message.
Here is my php:
if(isset($_POST['submitButton'])){
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $reason){
global $response;
if($type == "success") $response = "<div class='success'>{$reason}</div>";
else $response = "<div class='error'>{$reason}</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['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$human = 2;
//php mailer variables
$to = get_option('admin_email');
$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 = mail($to, $subject, strip_tags($message),
$headers);
if($sent) my_contact_form_generate_response("success",
$message_sent); //message sent!
else my_contact_form_generate_response("error",
$message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted'])
my_contact_form_generate_response("error", $missing_content);
}
?>
Here is my html for the "print error/success" and the form:
<?php echo $response; ?>
<form class="interest-form" action="<?php the_permalink(); ?>" method="POST">
<fieldset>
<legend>Anmäl Intresse:</legend>
<div class="row">
<div class="col-6">
<input type="text" class="form-control" placeholder="Namn" name="name" value="<?php echo esc_attr($_POST['name']); ?>">
</div>
<div class="col-6">
<input type="tel" class="form-control" placeholder="Telefonnummer" name="phone" value="<?php echo esc_attr($_POST['phone']); ?>">
</div>
</div>
<div class="row">
<div class="col">
<input type="email" class="form-control" placeholder="E-post" name="email" value="<?php echo esc_attr($_POST['email']); ?>">
</div>
<div class="col">
<input class="form-control" type="text" placeholder="<?php the_field('fb_8_1_plats'); ?> <?php the_field('fb_8_1_startdatum'); ?>" readonly name="plats_datum">
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="meddelande1">Meddelande:</label>
<textarea class="form-control" rows="3" name="message" value="<?php echo esc_attr($_POST['message']); ?>" id="meddelande1"></textarea>
</div>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<button type="submit" name="submitButton" class="btn btn-primary float-right">Skicka intresseanmälan</button>
</fieldset>
</form>
I really can't figure out what is wrong, I spent two full days just googling, trying and failing last weekend. After that I gave up and haven't looked at at for a week. Please help!
Edit: It doesn't load index.php, the path is still the same but it uses the template for index.php
I have no real experience with PHP, and so have just pulled bits of code from various answers to help construct a simple PHP contact form. I have spent two days trying to work out why various variations aren't working. I've included my code:
HTML :
<section class="form-section" id="form-section">
<div class="row headline">
<h3>Free Quotation</h3> </div>
<div class="row">
<form action="mailer.php" method="post" name="htmlform" class="contact-form" target="_blank">
<div class="col span-1-of-2">
<div class="row inputs">
<label for="name">Name</label>
<input name="name" placeholder="Your name" required="" type="text"> </div>
<div class="row inputs">
<label for="email">Email</label>
<input name="email" placeholder="Your email" required="" value="" type="email" class="required email"> </div>
<div class="row inputs">
<label for="business_name">Business Name</label>
<input value="" name="business_name" placeholder="Your business name" required="" type="text" class=""> </div>
</div>
<div class="col span-1-of-2 message-box-container">
<label class="text-box-label" for="message">In a few words, what are you looking for?</label>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<div class="row form-messages">
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try again</div>";
}
?> </div>
<div class="col span-2-of-3">
<div class="clear">
<input type="submit" value="Find Out More" name="subscribe" class="button"> </div>
</div>
</form>
</div>
</section>
This is my mailer.php form:
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$business_name = strip_tags(trim($_POST["business-name"]));
$business_name = str_replace(array("\r","\n"),array(" "," "),$business_name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "chussell#thegreenbuddha.co.uk";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_content .= "Business Name: $business_name \n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=1#form");
?>
When I have this on live preview both success and error messages display with PHP code. I have the file saved as a index.php. And when I submit it opens up the fresh page which is blank.
When I've added the new index.php and mailer.php to my cpanel, my website no longer displays!
Any suggestions or improvements?
Many thanks!
The following
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try gain</div>";
}
?>
Into
<?php
if($_GET['success'] == 1) {
echo '<div class="success">Thank You! We\'ll aim to follow up as soon as possible</div>';
}
if($_GET['success'] == -1) {
echo '<div class="error">Oops something went wrong, please try gain</div>';
}
?>
The following
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Into
if (empty($name) || empty($business_name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Please change the following also:
$business_name = strip_tags(trim($_POST["business-name"]));
Into
$business_name = strip_tags(trim($_POST["business_name"]));
I have a HTML Contact Form which I need validating in a certain way.
Instead of alerting the user in JavaScript if any fields have not been filled I prefer to show the words 'Field Required' below the fields which were left empty.
Here is my contact form contact.html:
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" />
<input type="submit" value="Submit" class="button" />
</form>
Here is my PHP form contact.php (Everything omitted apart from validation):
//Validation... I am building up an error message string to alert the user at the end (omitted)
$errormessage = '';
if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
$errormessage .= 'You have not entered your Name\n';
}
if(!isset($_POST['email']) || strlen($_POST['email']) < 1){
$errormessage .= 'You have not entered your Email Address\n';
}
if($errormessage != ''){ ?>
<script language="javascript" type="text/javascript">
alert('<?php echo "$errormessage" ?>');
window.location = 'contact.html';
</script>
<?php }
else {
$mail_to = 'info#email.co.uk';
$subject = 'Message from a site visitor '.$field_name;
$body_message = 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
}
As you can see my current validation builds up a string in PHP which is going to be alerted to the user at the end (omitted) however I want to replace this method by showing the string 'Field Required' below the HTML fields which have been left empty.
Another option if you are okay using some html5 features is to set the required attribute on the inputs.
required
This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.
Taken from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input
So your html would become:
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" required />
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" required />
<input type="submit" value="Submit" class="button" />
</form>
I wanted to answer your question without deviating from your approach.
If contact.html can be parsed by php, or it were simply changed to contactform.php, you could send a query string to it indicating which fields had errors and display a message below them.
contactform.php
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
<?php if (isset($_GET['name']) && $_GET['name'] == 1) {
echo '<br/>This field is required.';
} ?>
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" />
<?php if (isset($_GET['email']) && $_GET['email'] == 1) {
echo '<br/>This field is required.';
} ?>
contact.php
$error = FALSE;
$errors = array();
if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
$error = TRUE;
$errors[] = 'name=1';
}
if(!isset($_POST['email']) || strlen($_POST['email']) < 1){
$error = TRUE;
$errors[] = 'email=1';
}
$geterrors = (count($errors) > 1 ? implode('&',$errors) : $errors[0]);
if($error){ ?>
<script language="javascript" type="text/javascript">
window.location = 'contactform.php?<?php echo $geterrors; ?>';
</script>
...
I don't think my title does this question justice but it may get confusing and I don't want to extend the title over several lines.
Here goes:
I have a single page website which has a contact form with the below code:
<form class="move-down" name="contactform" method="post" action="contact-form-handler.php">
<div class="controls controls-row">
<input id="name" name="name" type="text" class="span3" placeholder="Name">
<input id="email" name="email" type="email" class="span3" placeholder="Email address">
</div>
<div class="controls">
<textarea id="message" name="message" class="span6" placeholder="Your Message" rows="7"></textarea>
</div>
<div class="controls pull-right">
<button id="contact-submit" type="submit" class="btn btn-default">Send it!</button>
</div>
</form>
As you can see its action is to call an external php file called "contact-form-handler", which is shown below:
<?php
$errors = '';
$myemail = 'hello#wunderful.co.uk';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= die(header('Location: #errorModal'));
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= die(header('Location: #errorModal'));
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' modal
header('Location: #thanksModal');
}
?>
<?php
?>
This has been working fine but as my new site is one page I don't want separate pages loading, nor do I just want to echo black text on a white background.
So my question is - How do I show the Bootstrap Modal window when the submit button is clicked, with php code from inside the external file AND without the page reloading?
I hope it can be done. If it can't can someone help me launch a modal that says error or thanks when the submit button is clicked?
yes you can. Since you are not using oop way you can do this
1) on page submit you will assign some $mail_send = true; after email is send
2) you fill then say <?php if ($mail_send) { ?> code for modal here <?php } ?>
3) Drop this header('Location: #thanksModal'); you do not need that.
Put $mail_send = true; instead of that.
that is all.