Reputation: 365
I'm having some trouble getting a form to properly email its contents to me, using ajax to show a thank you message rather than reload. Removing preventDefault() from the JS gets the form to send correctly, but obviously also causes a page redirect to the PHP file, which I don't want. Code included below, is there something obvious I've done wrong? Site is running on Wordpress, but I don't want to use a plugin as these seem to add extra elements that break the form design.
HTML
<form method="post" action="<?php echo get_template_directory_uri();?>/review-form-handler.php" id="websiteReviewForm">
<div class="formField">
<div class="inputEffect">
<input type="text" name="Website" required>
<hr>
<label for="Website">Your Website?</label>
</div>
<p>1 / 4</p>
</div>
<div class="formField">
<div class="inputEffect">
<input type="text" name="Name" required>
<hr>
<label for="Name">Your Name?</label>
</div>
<p>2 / 4</p>
</div>
<div class="formField">
<div class="inputEffect">
<input type="text" name="Email" required>
<hr>
<label for="Email">Your Email?</label>
</div>
<p>3 / 4</p>
</div>
<div class="formField">
<div class="inputEffect">
<input type="text" name="Phone" required>
<hr>
<label for="Phone">Your Phone Number?</label>
</div>
<p>4 / 4</p>
</div>
<input type="submit" name="submit" value="REVIEW MY WEBSITE">
</form>
JS
$('#websiteReviewForm').submit(function(e){
e.preventDefault();
$.ajax({
url:$(this).attr('action'),
type:'post',
data:$(this).serialize(),
success:function(){
$('#websiteReviewForm').hide();
$('.thankyouMessage').show();
}
});
});
PHP
<?php
if($_POST["submit"]) {
$recipient="MY EMAIL";
$subject="Form to email message";
$sender="Visix";
$senderEmail="MY EMAIL";
$website=$_POST["Website"];
$name=$_POST["Name"];
$email=$_POST["Email"];
$number=$_POST["Number"];
$mailBody="Name: $sender\nEmail: $senderEmail\nWebsite: $website\nName: $name\nEmail: $email\nPhone number: $number";
mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");
}
?>
Upvotes: 1
Views: 32
Reputation: 1074108
The problem is the way you're checking for the form in the PHP:
if($_POST["submit"]) {
Since you're not posting it via the normal mechanism trigged by the submit button, there's no submit
entry in the data sent to the server. (The value of a submit
button is only sent when the form is actually submitted via that button's activation.)
You can solve that by
Adding
<input type="hidden" name="submit" value="x">
...to the form
Or adding it in the ajax
call after serializing:
data: $(this).serialize() + "&submit=x",
Or just checking for one or more of the other fields that already exist
Upvotes: 1