user3066347
user3066347

Reputation:

Recieving JSON from AJAX Call with MongoDB

I am getting a users details from a MongoDB database like this:

$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
    json_encode($user);
    print_r($user);
}

I can get an entire JSON array from the AJAX but not individual elements - I get undefined:

$.ajax({
    type: 'json',
    url: '../scripts/getUser.php',
    method: 'GET',
    success: function(msg){
        alert(msg);
    }
});

The actual JSON is structured like this:

username: john
password: hello
email: [email protected]

I'm stuck.

Upvotes: 1

Views: 1141

Answers (3)

Vivek Kumar
Vivek Kumar

Reputation: 120

               success: function (response) 
                {
                if(response != 'error')
                {
                    //parse into JSON
                var jsonObj = JSON.parse(response);

                var HTML = '';
                          //extract single value using each 
                $.each(jsonObj, function(key, val) {

                    HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
                   +'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
                   +'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
                   +'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
                   +'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';

                });

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151112

You need to get the return value

$encoded = json_encode($user);
print_r($encoded);

The method you are using does not encode in place. It returns a left side value.

Upvotes: 0

kamesh
kamesh

Reputation: 2424

you returning array object from getUser.php but you display it as a normal variable

$.ajax({
    type: 'json',
    url: '../scripts/getUser.php',
    method: 'GET',
    success: function(msg){
    $.each(msg,function(key,value){
        alert(value.id);
});    
}
});

i guess this will work..

Upvotes: 1

Related Questions