Reputation: 938
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\n";
$msg .= "Email: $email\n";
$msg .= "Number: $number\n\n";
$msg .= "$message\n";
$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.
Upvotes: 0
Views: 271
Reputation: 4136
You can not redirect from ajax
call. If you are using header
function it will print many header data in ajax success.
Header data is the Strange Result
you are getting ...
remove header("Location: [website address here]");
And if you want to redirect after success, do it like this in ajax success
block
if (data == "Correct") {
window.location = '[website addresss here]';
}
Upvotes: 1
Reputation: 9823
Remove header("Location: [website address here]")
from your mailer.php
page
And
$.ajax({
type: "POST",
url: '/lib/mailer.php',
data: {
name: $("#name").val(),
email: $("#email").val(),
number: $("#number").val(),
message: $("#message").val()
},
async:false, // <---- Add this fella here
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');
}
}
});
Upvotes: 0
Reputation: 1015
It is not matching the word. Use
if($.trim(data) == 'Correct')
Hope it will help.
Upvotes: 1