如何使用Jquery AJAX从PHP json_encode读取JSON数据

如何使用Jquery AJAX从PHP json_encode读取JSON数据

问题描述:

BEEN at this for days. Using jquery ajax to perform somethings and trying to get a json encoded response from my server. Not sure why this is now working for me.

Below is my Javascript function

function checkFriendsEmail(friendsEmail){ 
var request = $.ajax({          
    url : 'http://localhost/loginsentology/serverside/checkfriendexist2.php',
    type: 'POST',
    data: {
        'checkfriend' : 'checkfriend',
        'friendsemail' : friendsEmail,              
    },
    success: function(data) {               
        console.log(data); <<<-- Comes back to my console as a JSON obj
        console.log(data.nouser); <<-- Comes back undefined
    }

I get this result in my console. { "nouser" : ["noUserExist"] } <<<----- How do I grab this.

MY PHP is below

$fdarray = array();
$_db = DB::getInstance();
$_query = $_db->query('SELECT * FROM users WHERE email = ? ', array($_POST['friendsemail']));
$results = $_query->results();
$numberOfRows = $_db->numberOfRows();
if ($numberOfRows == 0) {
    //$noUserExist = 'NoUserExist';
     $fdarray['nouser'] = array();
    array_push($fdarray['nouser'], 'noUserExist');
    echo json_encode($fdarray);
    return false;
}
else {
    //friends email exist in users db --> now we must check to see if friend has devices
     $friendsEmail = $results[0]->email;
    if ($_POST['friendsemail'] == $friendsEmail) {
        $id = $results[0]->id;
        $_db2 = DB::getInstance();
        $_query2 = $_db2->query('SELECT * FROM devices WHERE userid = ? ', array($id));
        $results2 = $_query2->results();
        $numberOfRows2 = $_db2->numberOfRows();
        if ($numberOfRows2 == 0) {
            //user has no devices attached to name
             $fdarray['userexist'] = array();
            $fdarray['nodevices'] = array();
            array_push($fdarray['userexist'], true);
            array_push($fdarray['nodevices'], 'noDevicesForUser');
            echo json_encode($fdarray);
            return false;
        }
        else {
            $fdarray['userexist'] = array();
            $fdarray['devices'] = array();
            array_push($fdarray['userexist'], true);
            for ($i = 0; $i < $numberOfRows2; $i++) {
                array_push($fdarray['devices'], $results2[$i]->devicename);
            }
            //end for statement
        }
        //end number of rows2
         echo json_encode($fdarray);
    }
    //end firendsemail == firendsemail
}

I just figured it out. I was print_r($_POST) before the json_encode.

Judging by the results you get back { "nouser" : ["noUserExist"] } - notice the square brackets - the value you want is stored in an array, so you would need:

console.log(data.nouser[0]);

If the console.log(data.nouser); statement is returning

{ "nouser" : ["noUserExist"] }

Then you can try

console.log(data.nouser[0]);

which should return noUserExist.

You need to specify you are sending json object back to the browser before echo it out in your php code.

header("Content-type: application/json");

In you ajax function, you also want to specify the dataType is json

var request = $.ajax({          
    url : 'http://localhost/loginsentology/serverside/checkfriendexist2.php',
    type: 'POST',
    data: {
        'checkfriend' : 'checkfriend',
        'friendsemail' : friendsEmail,              
    },
    success: function(data) {               
        console.log(data); //<<<-- Comes back to my console as a JSON obj
        console.log(data.nouser); //<<-- Comes back undefined
        console.log(data.nouser[0]);
    },
    dataType: 'json'
    });