I am working on a website and I can't seem to get my submit button to send the message unless I redirect it to the PHP file instead of displaying the message on the original contact page. I'm pretty sure the issue is within my HTML file but I can't seem to figure out how to fix it. Any help is much appreciated!
$(function() { $('#contactForm').validate({ "rules":{ "contactName":"required", "contactEmail":{ "required":true, "email":true }, "contactSubject":"required", "contactMessage":"required" }, submitHandler: function(form) { $.ajax({ type: "post", url: "sendEmail.php", data: $(form).serialize(), success: function(response) { console.log(response); var getJson = JSON.parse(response); if (getJson.success) { alert('Your message was sent!'); } else { alert('There was an error, please try again!'); } }, }); } }); });
<?php // Replace this with your own email address $siteOwnersEmail = '********'; if($_POST) { $name = trim(stripslashes($_POST['contactName'])); $email = trim(stripslashes($_POST['contactEmail'])); $subject = trim(stripslashes($_POST['contactSubject'])); $contact_message = trim(stripslashes($_POST['contactMessage'])); // Check Name if (strlen($name) < 2) { $fail['name'] = "Please enter your name."; } // Check Email if (!filter_var($email,FILTER_VALIDATE_EMAIL)) { $fail['email']="Please enter a valid email address."; } // Check Message if (strlen($contact_message) < 15) { $fail['message'] = "Please enter your message. It should have at least 15 characters."; } // Subject header('Content-type: application/json'); if (empty($fail)) { ini_set("sendmail_from", $siteOwnersEmail); // for windows server if ($subject=='') $subject="Contact Form Submission"; $message = ''; $message .= "Email from: " . $name . "<br />"; $message .= "Email address: " . $email . "<br />"; $message .= "Message: <br />"; $message .= $contact_message; $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />"; $from = $name . " <" . $email . ">"; $headers = "From: " . $from . "\\r\\n"; $headers .= "Reply-To: ". $email . "\\r\\n"; $headers .= "MIME-Version: 1.0\\r\\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\\r\\n"; # Check if email sent if (mail($siteOwnersEmail, $subject, $message, $headers)) { # Report true if sent $return['success'] = true; } else { $return['success'] = false; $return['msg'] = "Something went wrong. Please try again."; } } else { $return['success'] = false; # end if - no validation error $return['errors']['name'] = (isset($fail['name'])) ? $fail['name']: false; $return['errors']['email'] = (isset($fail['email'])) ? $fail['email']: false; $return['errors']['message'] = (isset($fail['message'])) ? $fail['message']: false; } # Display response die(json_encode($return)); } ?>
<div id="contact-form" class="contact-form"> <form name="contactForm" id="contactForm" method="post" action=""> <div class="form-group wow fadeInDown" data-wow-duration="500ms" data-wow-delay=".6s"> <input type="text" placeholder="Your Name" class="form-control" name="contactName" id="contactName"> </div> <div class="form-group wow fadeInDown" data-wow-duration="500ms" data-wow-delay=".8s"> <input type="email" placeholder="Your Email" class="form-control" name="contactEmail" id="contactEmail"> </div> <div class="form-group wow fadeInDown" data-wow-duration="500ms" data-wow-delay="1s"> <input type="text" placeholder="Subject" class="form-control" name="contactSubject" id="contactSubject"> </div> <div class="form-group wow fadeInDown" data-wow-duration="500ms" data-wow-delay="1.2s"> <textarea rows="6" placeholder="Message" class="form-control" name="contactMessage" id="contactMessage"></textarea> </div> <div> <button class="wow fadeInDown submitform" data-wow-duration="500ms" data-wow-delay="1.4s">Submit</button> </div> </form> </div>
From what I can see you have flaws in both your PHP and your JavaScript. First on your PHP, you have a syntax error (too many end braces). I have notated areas where changes are required:
if(!empty($_POST)) {
$siteOwnersEmail='***********';
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
if (strlen($name) < 2) {
$fail['name']="Please enter your name.";
}
# Use the built-in email address checker
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$fail['email']="Please enter a valid email address.";
}
if (strlen($contact_message) < 15) {
$fail['message']="Please enter your message. It should have at least 15 characters.";
}
# Create header
header('Content-type: application/json');
# YOU NEED TO CHECK EMPTY. If you do simply !$fail, you may get an undefined variable warning
if (empty($fail)) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
if ($subject=='')
$subject="Contact Form Submission";
# You have to first set this or you get a warning
$message = '';
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
$from = $name . " <" . $email . ">";
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
# Check if email sent
if (mail($siteOwnersEmail, $subject, $message, $headers)) {
# Report true if sent
$return['success'] = true;
}
else {
$return['success'] = false;
$return['msg'] = "Something went wrong. Please try again.";
}
}
else {
$return['success'] = false;
# end if - no validation error
$return['errors']['name'] = (isset($fail['name'])) ? $fail['name']: false;
$return['errors']['email'] = (isset($fail['email'])) ? $fail['email']: false;
$return['errors']['message'] = (isset($fail['message'])) ? $fail['message']: false;
}
# Display response
die(json_encode($return));
}
In your JavaScript, you need a few changes:
<script>
// Start with document ready
$(function() {
$('#contactForm').validate({
// Create some rules for your form
"rules":{
"contactName":"required",
"contactEmail":{
"required":true,
"email":true
},
"contactSubject":"required",
"contactMessage":"required"
},
// Submit on validation
submitHandler: function(form) {
$.ajax({
type: "post",
url: "sendEmail.php",
data: $(form).serialize(),
// I generally do success here...
success: function(response) {
// Check that it's returning something
console.log(response);
// Should return json, so parse it (or change dataType to json)
var getJson = JSON.parse(response);
// Message was sent
if (getJson.success) {
alert('Your message was sent!');
}
// There was an error
else {
alert('There was an error, please try again!');
}
},
});
}
});
});
</script>
Last note, make sure you add error_reporting(E_ALL); ini_set('display_errors',1);
error_reporting(E_ALL); ini_set('display_errors',1);
at the top of your PHP pages and fix the warnings you receive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.