John Doe John Doe - 1 year ago 80
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
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?

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


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



} else {
ajax.SetText("Send mail");
$.get("unsent.html", function(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,
but it still doesnt work. Does anyone know why? Any thing would be appreciated, thanks.

Answer Source

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:


This might give you something similar to:


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:


I strongly believe this would be the case. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download