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: me@mailserver.com

I'm stuck.

Answers


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.


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..


               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>';

                });

Need Your Help

Style Unordered List Independently From Parent Unordered List

css wordpress navigation html-lists

I'm not sure if I formulated the question correctly, but let me try to explain what I want to achieve.

Parse HTML from local file

python html google-app-engine lxml

I'm using Google App Engine with Python. I want to get the tree of a HTML file from the same project as my Python script. I tried many things, like using the absolute url (e.g

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.