Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  188] [ 5]  / answers: 1 / hits: 25243  / 12 Years ago, fri, may 4, 2012, 12:00:00

Javascript/JQuery noob here, so apologies.



I'm using .ajax to get a JSON object then the code below to loop through and append the fields to the page. Easy.



$.each(data, function(i, item) {
$(#div-ipos).append(
<img src= + item.user.avatar_small_url + >&nbsp;
+ item.user.first_name
+ <hr /><br />
);
});


It works and the output is as expected, complete with the avatar path passed into an <img> tag.



However I get the following error:




TypeError: 'undefined' is not an object (evaluating 'item.user.avatar_small_url')




What do I need to do to that variable to make it behave properly in this context?


More From » jquery

 Answers
47

Use console.log(data); before your $.each to check what's in it. Most likely the server response contains an extra array element with no user. So the JSON could look like:



[{user:{avatar_small_url:foo,first_name:bar}},
{user:{avatar_small_url:bar,first_name:foo}},
{something_other_than_user:9000}]


See how the last array element doesn't have a user. If you have access to the server code, you may want to modify it so there is always a user, or you may modify your Javascript so that it exits early if the user field doesn't exist with something like: if(typeof item.user == 'undefined') return;


[#85788] Thursday, May 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchell

Total Points: 95
Total Questions: 110
Total Answers: 87

Location: Gabon
Member since Thu, Jul 15, 2021
3 Years ago
mitchell questions
;