0

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?

1 Answer 1

4

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!");
               }
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

That did it! I didn't realise that the for..in loop worked differently to the foreach loop. Thanks for the help :)
Was just waiting for Stack Overflow to let me, due to the 5 minute limit. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.