I have a PHP contact form that I'm using with jQuery's AJAX method, but I'm getting very strange results with the "success:" function.
Here's the PHP contact form:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
$msg = "Name: $name
";
$msg .= "Email: $email
";
$msg .= "Number: $number
";
$msg .= "$message
";
$recipient = "[recipients here]";
$subject = "Contact Us - $name";
$mailheaders = "From:$email";
$success = mail($recipient, $subject, $msg, $mailheaders);
if ($success) {
echo ('Correct');
} else {
echo ('Failed');
}
header("Location: [website address here]");
?>
Here's the jQuery AJAX method:
$("#contact-form").submit(function (event) {
$.ajax({
type: "POST",
url: '/lib/mailer.php',
data: {
name: $("#name").val(),
email: $("#email").val(),
number: $("#number").val(),
message: $("#message").val()
},
success: function (data) {
//$("#contact-form")[0].reset();
alert(data);
if(data === 'Correct') {
alert('Data is correct');
}
else if (data !== 'Correct') {
alert('Data is not equal to correct');
}
else {
alert('Else statement');
}
}
});
event.preventDefault();
return false;
});
Now, when I fill in the form and click submit, the PHP receives the right data and successfully sends the email, and echo's "Correct". An alert pops up saying "Correct". But then, instead of the next alert being "Data is correct", it is "Data is not equal to correct".
I have no idea what's going on here for that to happen. I'm assuming I must be making a really stupid mistake somewhere but can't seem to figure it out.