Trying to set up a contact form. Form submits email and optionally CCs sender. If javascript is enabled, the form submits to contact-ajax.php (to replace the form with a thanks message), otherwise it submits to contact.php (to redirect to a thanks page). The fallback form works fine, but every time the ajax form fires it also sends a completely blank email (to both sender and recipient, if CC option is checked). I can't figure out why this is occurring. Any insight would be appreciated.
Form HTML:
<form method="post" id="email_form" name="email_form" action="contact.php">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" placeholder="John Doe" /><br />
<label for="email">Email Address:</label><br />
<input type="text" name="email" id="email" placeholder="[email protected]" /><br />
<label for="subject">Subject </label></td><br />
<input type="text" name="subject" id="subject" placeholder="Subject" /><br />
<label for="message">Message:</label></td><br />
<textarea cols="35" rows="5" name="message" id="message" placeholder="Your Message"></textarea><br />
<input type="checkbox" name="cc" id="cc" checked value="Yes" /><label for="cc"> Send yourself a copy of this message</label><br />
<input class="submit pulldown button" name="submit" id="submit" type="submit" value="Send Message" />
</form>
Javascript:
$(document).ready(function() {
$('#email_form #submit').click(function(event) {
event.preventDefault();
$.ajaxSetup ({
cache: false
});
$.ajax({
type: 'POST',
url: 'contact-ajax.php',
data: $("#email_form").serializeArray(),
success: function(msg) {
if(msg=='Mail sent') {
alert(msg);
}
else {
alert('Error sending mail. Please try again.');
}
},
error: function(ob,errStr) {
alert('Error sending mail. Please try again.');
}
});
return false;
});
});
PHP form called by script (contact-ajax.php):
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$email_subject = $_POST['subject'];
$message = $_POST['message'];
$today = date('r');
$email_from = "[email protected]";
$to = "[email protected]";
$email_body = "On $today $name wrote:\n"."$message";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
if (isset($_POST['cc'])) {
$headers .= "CC: $visitor_email \r\n";
}
$headers .= "X-Mailer: PHP/". phpversion();
mail($to,$email_subject,$email_body,$headers);
if(mail($to, $subject, $body, $headers)) {
die('Mail sent');
}
else {
die('Error: Mail failed');
}
}
?>
The non-Ajax php script (contact.php) is identical, except that it ends with header('Location: thanks_page.html'); instead of the last if statement.
Blank emails contain no subject or message body, but From, Reply-To, and CC fields are all filled in exactly as they are in the correct (non-empty) message. I've been trying to figure out the problem for a few days now but can't seem to track it down.