I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.
I've attempted the fixes suggested in: How do I make an HTML button not reload the page
by using either the <button>
element or use an <input type="button"/>
. and also the fixes suggested in: prevent refresh of page when button inside form clicked
by adding onclick="return false;"
.
Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.
I also updated my PHP to reflect the name changes of the type.
My PHP is:
<?php
if(isset($_POST['submit'])){
$to = "example@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
?>
My HTML is:
<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..
EDIT:
I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:
1:
$(function() {
$('#contactForm').on('submit', function(e) {
$.post('index.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
2:
$("#contactForm").submit(function(e) {
e.preventDefault();
});
3:
I also tried the answer offered to me by Harsh Panchal.