Diane Diane - 2 months ago 17
Ajax Question

ajax success data assignment to variables with data[0] is undefined

I am trying to select data from a database in javascript code using ajax which calls a php script with a mysql query. The pgp code is working correctly, as I can view the ajax success results with an alert. But when I try to assign the data to variables, they show in the Console as undefined or NaN. Here is my code:

function zoomBldg() {

bldgId = document.getElementById("bldgzoom").value;

var bldgStreetAddress,zoomLat,zoomLng,bldgDescription,bldgDefaultPic,zoomCenter;

console.log('bldgId',bldgId);

$.ajax({
url: "getBldgInfoWajaxGETtest.php",
type: "POST",
data: {bldgId : bldgId},
dataType: 'json',
cache: false,
success: function(data)
{
alert(JSON.stringify(data));
bldgStreetAddress = data[0];
zoomLat = data[1];
zoomLng = data[2];
bldgDefaultPic = data[3];

},
error: function (request, status, error) {
console.log(error);
}
});

zoomLat = parseFloat(zoomLat);
zoomLng = parseFloat(zoomLng);
zoomCenter = {lat:zoomLat, lng:zoomLng};

console.log('bldgId',bldgId);
console.log('bldgStreetAddress',bldgStreetAddress);
console.log('zoomLat',zoomLat);
console.log('zoomLng',zoomLng);

}


The results that appear in the alert is:

[{"0":"50 Fremont Street","1":"37.790505","2":"-122.397259","3":null,"building_address":"50 Fremont Street","latitude":"37.790505","longitude":"-122.397259","default_pic":null}]

The results in the Console are:

bldgId 17
bldgId 17
bldgStreetAddress undefined
zoomLat NaN
zoomLng NaN

I copied the data[0] etc code from an example online, but I am not too familiar with json so I'm not sure why that isn't working.

Answer

Understand the code your copying and pasting. Learn how json works and what JSON.parse and JSON.stringify do.

Look at your json structure. The information is in an array. so data is an array. Each key of the object is a string not a integer.

data[0]["1"]

You also have the success function being called later on. Thus the values would not be set. To fix this I would do any code that needs the values in or from the success callback.

            success: function(data)
            {
                alert(JSON.stringify(data));
                bldgStreetAddress = data[0]["0"];
                zoomLat = data[0]["1"];
                zoomLng = data[0]["2"];
                bldgDefaultPic = data[0]["3"];

                zoomLat = parseFloat(zoomLat);
                zoomLng = parseFloat(zoomLng);
                zoomCenter = {lat:zoomLat, lng:zoomLng};

    console.log('bldgId',bldgId);
    console.log('bldgStreetAddress',bldgStreetAddress);
    console.log('zoomLat',zoomLat);
    console.log('zoomLng',zoomLng);

            },