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

后端 未结 6 1259
傲寒
傲寒 2021-01-23 14:31

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

function check() {
    $.ajax({
               


        
相关标签:
6条回答
  • 2021-01-23 14:34

    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);
        });
    }
    
    0 讨论(0)
  • 2021-01-23 14:34

    Ajax may not be returning a boolean true or false, rather a string.

    So try and put true in double quotes:

    if(data=="true")

    You can also use the trim function on data to ensure no whitespace is present in the returned data, like so:

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

    0 讨论(0)
  • 2021-01-23 14:42

    you just echo the $result like this

    ajax not returning value so that we have to echo it.

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

    and then should be like this

    function check() {
    $.ajax({
        url: "status.php"
    }).done(function(data) {
        if(data == "true"){
            alert("true");
        } else {
            alert("false");
        }
    });   }
    
    0 讨论(0)
  • 2021-01-23 14:42

    Just Remove Type checking i.e '===' replace with '=='

    function check() {
        $.ajax({
            url: "status.php"
        }).done(function(data) {
            if(data == true){
                alert("true");
            } else {
                alert("false");
            }
        });
    }
    
    0 讨论(0)
  • 2021-01-23 14:47

    Use

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

    and on status.php use

    echo json_encode(status()); 
    
    0 讨论(0)
  • 2021-01-23 14:52

    You cannot get the response by return method in ajax. to get value "echo" whatever the result in the function , like

    function status(){
        if(logged() === true) {
            $result = "1";
        } else {
            $result = "0";
        }
        echo $result;exit;
    }
    

    you will get the value 1 or 0 in your ajax success function

    0 讨论(0)
提交回复
热议问题