I have read so many solutions about preventing page reload from form submission, most of them are to return false with a "JQuery script" or preventDefault()
.
The problem is, if you prevent the page reload with Javascript or JQuery, the code won't be executed, so in my case, the email will not be sent. So, how could I run both?
Here is my HTML form.
<form id="myform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<p><input class="w3-input w3-padding-16" type="text" placeholder="name" required name="name"></p>
<p><input class="w3-input w3-padding-16" type="email" placeholder="email" required name="email"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="subject" required name="subject"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="comment" required name="comment"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
My PHP code to collect data and send email:
<?php
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = form($_POST["name"]);
$email = form($_POST["email"]);
$subject = form($_POST["subject"]);
$comment = form($_POST["comment"]);
$to = "myemail@gmail.com";
mail($to,$subject,$comment,$email);
}
function form($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
My JQuery:
$(document).ready(function() {
$(document).on('submit', '#myform', function() {
return false;
});
});