Dangling Cruze
Dangling Cruze

Reputation: 3433

Getting undefined when accessing json's value in $.each

This is the each that traverses the response json object that I an receiving via ajax call.

$.each(response, function(i, item) {
    alert(item.pin + item.place);
    selected = response[i].pin.substr(0, zip.length);
    remain = response[i].pin.substr(zip.length);
    $(".zip-drop").append("<p class='zip-suggest'><span class='suggest-pin'><b>"+selected+"</b>"+remain+"</span><span class='suggest-place'>"+item.place+"</span></p>");
    return i < Object.keys(response).length - 1;
});

Everything is working fine, but in the console i'm getting undefined item.pin though the alert is producing the desired result. This undefined problem makes the ajax call stay for a long long time. I'm using a loader image and it stays forever once the ajax call is made.

Any solution for removing the undefined error. I can't understand why?

Upvotes: 1

Views: 105

Answers (1)

Shanimal
Shanimal

Reputation: 11718

you could also remove all that and put a check at the beginning... eg.

if(!response[i].pin) return false; 

cheers :)

Upvotes: 1

Related Questions