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 + "> "
+ 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?
Use
console.log(data);before your$.eachto check what’s in it. Most likely the server response contains an extra array element with no user. So the JSON could look like: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;