John Doe John Doe - 2 months ago 5
Ajax Question

How to get return data from PHP file via AJAX?

I'm trying to make a contact form with PHP and AJAX. The email sends and all but it always says

"Failed to send!"
even in the console it says
"true"
which should result in the html
"Message Sent!"


So I wrote this in the end of my PHP script:

if (!$mail->send()) {
echo $mail->ErrorInfo;
} else {
echo "true";
}


and that should mean that via AJAX the output data I get should be one of those, correct?

ajax.SetText("Sending...");
$.post("sendmail.php", {
name: userName, email: userEmail, comments: userComments, business: currentBusiness, website: currentWebsite
}, function(data) {
if(data == "true") {

ajax.SetText("Sent!");
console.log(data);


$.get("sent.html", function(sentData){

$("#content").html(sentData);

});

} else {
ajax.SetText("Send mail");
console.log(data);
$.get("unsent.html", function(sentData){

$("#content").html(sentData);

});


}

ajax.isSubmiting = false;
});


This is the jQuery^

So basically if the email is sent I want the return to be "true" so then I could put the appropiate information on the page like "The message was sent!" But in this case, whether it fails to send or succeeds, it never returns true. I have also tried, in the php file,
print_r("true")
and
die("true")
but it still doesnt work. Does anyone know why? Any thing would be appreciated, thanks.

Answer

Looks like the system is taking "true" to be a keyword. Try putting OK or something. Also check if you aren't outputting an extra line. You can do this by checking with .trim().

if (data.trim() == "true") {

To check such kind of issues, try on the console using encodeURI() function:

console.log(encodeURI(data));

This might give you something similar to:

console

I created an Enter line on the output. This might not match if you check with:

data == "true"

So you might need to use the trim() function here. Look at the below for more information:

console

I strongly believe this would be the case. :)