Passing a list of objects to JavaScript from Controller method using Ajax

I have a controller method GetNearbyUsers which returns a list of users as a JsonResult. I am trying to call the method using the following ajax function:

function getNearbyUsers(interest) {
    $.ajax(
    {
        type: "POST",
        url: "/Interest/GetNearbyUsers",
        data: { "interest": interest},
        success:
            function (result) {
                console.log(result);
                for (var item in result) {
                    console.log(item.username);
                }
            },
        error: function (req, status, error) {
                    window.alert("Error!");
               }
    });
}

At the moment I'm just trying to display the usernames in the console to make sure it is working and I will move on from their. The controller method works fine and returns the correct JsonResult; in fact printing 'result' gives:

[Object, Object, Object, Object, Object]
0: Object
Id: Object
Interests: Array[3]
LastUpdated: "/Date(1367419763994)/"
Location: Array[2]
Password: "password"
UserName: "user1"
__proto__: Object
1: Object
2: Object
3: Object
4: Object

So the Ajax call seems to be working and getting the right data. However, when I try accessing the objects in the list e.g. item.username, it tells me that username is undefined. When I just do console.log(item) it just prints the index. I also tried using JSON.parse on 'result' but it gives me the 'Unexpected token o' error. Any ideas?

Answers


Try this:- Note- Casing is important. it should be UserName not username

for..in loop gets index not the item, so you should do result[idx]

Your default return is already in JSOn so you dont need to do JSON.parse on your result.

function getNearbyUsers(interest) {
    $.ajax(
    {
        type: "POST",
        url: "/Interest/GetNearbyUsers",
        data: { "interest": interest},
        success:
            function (result) {
                console.log(result);
                for (var idx in result) {
                    console.log(result[idx].UserName);
                }
            },
        error: function (req, status, error) {
                    window.alert("Error!");
               }
    });
}

Need Your Help

Cannot access data in JSON response

javascript json

I am trying the access the json response from the server, using the following code. According to firebug, my server is outputting what looks like a valid json response as follows:

Carousel slider loads first but images take time to load

javascript jquery css twitter-bootstrap

I am using carousel slider in my website using bootstrap.