CurlyCream CurlyCream - 4 months ago 9
Ajax Question

Accessing java script properties

I am trying to access the properties of javascript objects returned by a ajax response. But it says "Cannot read property '0' of undefined". However if i hard code the same object in a variable and read, i am able to access it.

// code that throws "cannot read........." error

$.get('/home/address/city.html', { zipcode: zipcode }, function(ListJSON) {
var tempdata = Stringify(ListJSON);
alert(tempdata);
alert(tempdata["items"][0]["city"]);


This gives the output for first alert and second alert throws error.
output of alert(tempdata);

{"identifier":"branch","label":"name","items":{"0":{"name":"1234 ABCD AVE ","branch":"555 ", "city":"BLR "}}}


// working code

$.get('/home/address/city.html', { zipcode: zipcode }, function(ListJSON) {
var tempdata = {"identifier":"branch","label":"name","items":{"0":{"name":"1234 ABCD AVE ","branch":"555 ", "city":"BLR "}}};
alert(tempdata);
alert(tempdata["items"][0]["city"]);


output of first alert

{"identifier":"branch","label":"name","items":{"0":{"name":"1234 ABCD AVE ","branch":"555 ", "city":"BLR "}}}


output of second alert

BLR

Answer

The difference between them is the hard code working version isn't using string. You are assigning an object to tempdata whereas in first version you use var tempdata = Stringify(ListJSON); which I assume returns JSON.stringify(ListJSON)

You want to work with object, not string

Try

$.getJSON('/home/address/city.html', { zipcode: zipcode }, function(ListJSON) {

     alert(ListJSON["items"][0]["city"]);