Reputation: 1501
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?
Upvotes: 1
Views: 1288
Reputation: 9056
chartDesc
variable scope is tied to the success
function, that's why outside it, the variable is undefined
.
in Javascript
functions create scopes for variables defined with var
Upvotes: 1
Reputation: 87073
make your
console.log(xArr);
console.log(yArr);
within success
function. and declire chartDesc
variable outside of success function,
console log outside of success function execute immediately when function called, but it takes some time to insert value of xArr
and yArr
due to success function execution. so you get nothing in you log.
Upvotes: 0
Reputation: 337560
You are declaring the chartDesc
variable inside the AJAX callback function, so it is outside the scope of your later reference to it.
To fix this, remove the var
from the start of the line, and instead declare it at the top of the function with the xArr
and yArr
variables:
var xArr = [];
var yArr = [];
var chartDesc = "";
Upvotes: 3