Reputation: 47
I am trying to create a simple form in WordPress to send an email after the submit button is clicked, however when the submit button is clicked the page refreshes and I get redirected to my 404 page. This happens regardless of where I specify for it to redirect to, even if I say to make it redirect to the same page. Is there anyway I can use the mail function and avoid getting the 404 error that I've been running into? I would appreciate any help in locating this! Thank you!
<form method="post">
<h1 class="sectionHeader title">Contact</h1>
<div id="inputContainer">
<div class="flexChildInput" id="nameInput">
<h4 class="contactLabels">Name</h4>
<input type="text" name="name" required />
</div>
<div class="flexChildInput" id="emailInput">
<h4 class="contactLabels">Email</h4>
<input type="text" name="email" required />
</div>
</div>
<div id="commentsContainer">
<h4 class="contactLabels">Comments</h4>
<textarea name="comments" id="" cols="30" style="height: 25vh;" required></textarea>
</div>
<input name="action" hidden />
<div id="submitContainer">
<input type="submit" value="Submit" />
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit']) && !empty($_POST(['name'])) && !empty($_POST(['email'])) && !empty($_POST(['comments']))) {
$to = $_POST['[email protected]'];
$subject = $_POST['name'] + " has sent you a message!";
$message = $_POST['comments'];
$from = $_POST['email'];
$headers = "From:" . $from;
//(mail($to, $subject, $message, $headers);
if (mail($to, $subject, $message, $headers)) {
echo "Mail Sent.";
} else {
echo "failed";
}
}
}
?>
</div>
</form>
Upvotes: 0
Views: 59
Reputation: 371
It's so simple to achieve that. Refer the following sample code:
<?php
if(isset($_POST['submit'])){
//code to be executed
}else{
//code to be executed
}
?>
<html>
<head></head>
<body>
<form method="post" action="">
<input type="submit" name="submit">
</form>
</body>
</html>
The PHP Script will only run if the submit button is clicked.
Upvotes: 1