user2773530 user2773530 - 7 months ago 13
Javascript Question

How to get true or false from PHP function using AJAX?

I tested status.php return value with var_dump($result) and alerted it out in check() function like this:

function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
alert(data);
});
}


and it did return true or false depending on situation, but when I check if data is true or false inside of check() function it always returns false.

status.php:

<?php
function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
return $result;
}
status();
?>


check() function: always alerts "false" even though sometimes should be "true"

function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data === true){
alert("true");
} else {
alert("false");
}
});
}

Answer

You're not sending the return value of the status() function back to PHP. Use:

echo json_encode(status());

And change the AJAX call to expect a JSON response.

function check() {
    $.ajax({
        url: "status.php",
        dataType: 'json'
    }).done(function(data) {
        alert(data);
    });
}