I have this function:
function getReport(name,x) {
var xArr = [];
var yArr = [];
$.ajax({
async: false,
type: "POST",
//async: false,
//dataType: "json",
url: "reportAjax.php",
data: "name="+ name,
success: function(data){
var json = $.parseJSON(data);
var chartDesc = json.INFO.DESC;
$.each(json.RESULT, function(i, object) {
$.each(object, function(property, value) {
//alert(property + "=" + value);
if (property == x) {
xArr.push(value);
}
else {
yArr.push(parseInt(value));
}
});
});
}
});
console.log(xArr);
console.log(yArr);
console.log(chartDesc);
drawChart(xArr,yArr,chartDesc);
}
For some reason, I can see in the console.log the values of xArr and yArr, but I get chartDesc is not defined for chartDesc.
If I move the console.log(chartDesc) line to be under this line var chartDesc = json.INFO.DESC I can see it properly.
Why is that?
You are declaring the
chartDescvariable inside the AJAX callback function, so it is outside the scope of your later reference to it.To fix this, remove the
varfrom the start of the line, and instead declare it at the top of the function with thexArrandyArrvariables: