Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Accessing a JSON object?

I get the following back from an $.ajax({ POST.....

[{"total_votes":1,"options":[{"id":40,"vote_count":0,"users":[]},{"id":41,"vote_count":1,"users":[{"photo":"xxxxxxxxxxx.png","name":"XXXXX,"id":1}]},{"id":42,"vote_count":0,"users":[]}]}]

so I try to get total_votes with:

    success: function(e) {
        console.log(e['total_votes'])       
    }

also try to get

        console.log( e['options'].length() )
        console.log( e['options'][0]['id'] )

Suggestions on why I keep getting undefined? Also is there a better way to loop through options?

Thanks

like image 251
AnApprentice Avatar asked Jun 13 '26 13:06

AnApprentice


2 Answers

Your root object is an array, so you would need to do something like e[0]['total_votes']. Also the length of an array is not a function its a property so you would want to do e[0].options.length or e[0]['options'].length.

like image 116
Kevin Decker Avatar answered Jun 15 '26 03:06

Kevin Decker


Loop through them with $.each()

like image 28
AlienWebguy Avatar answered Jun 15 '26 01:06

AlienWebguy