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.