I just can't seem to figure out why this form is not submitting. It is a simple contact form that I am trying to build.
html:
<div id="contact">
<div >
<form method="post" action="form.php">
<h2>Contact Us</h2>
<input type="name" placeholder="Name and Surname" required />
<input type="email" placeholder="Email" required />
<textarea type="message" placeholder="Message" required></textarea>
<input type="submit" placeholder="submit" />
</form>
</div>
</div>
php:
if(isset($_POST['email']) && $_POST['email'] != '') {
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_subject = "New Form Submission";
$email_body = "User Name: $name.\n".
"User Email: $visitor_email.\n\n".
"User Message: $message\n";
$to = "[email protected]";
$headers = "From: $email_from \r\n";
$headers = "Reply-To: $visitor_email \r\n";
mail($to, $email_subject, $email_body, $headers);
header ("Location: ../index.html");
echo '<script> alert("Message received. We will get back to you soon.") </script>';
}
}
And I am also trying to make an alert that the message has been sent, but that hasn't been working either.
Thanks for the help in advance for the help.
CodePudding user response:
<input type="email" placeholder="Email" required />
is missing the name="email"
attribute. It should be
<input type="email" name="email" placeholder="Email" required />
.
As for the alert, you can't add code after a header('Location...')
redirect because the browser will ignore the content and just redirect before showing the page content. Better to redirect to a PHP page and add a query string like this:
header( 'Location: thanks.php?message=alert' );
exit();
and in thanks.php
:
if ( isset($_GET['message']) && $_GET['message'] == 'alert' ) {
echo '<script> alert("Message received. We will get back to you soon.") </script>';
}
CodePudding user response:
You need to add name attribute with fields. Because only form elements with a name attribute will have their values passed when submitting a form.
So add name attributes in your fields.
<input name="name" type="text" placeholder="Name and Surname" required />
<input name="email" type="email" placeholder="Email" required />
<textarea name="message" placeholder="Message" required></textarea>
<input type="submit" placeholder="submit" />