Reputation: 4792
I am using jQuery and I have the following code:
var result = [];
if ( some_condition ) {
result = [...]
} else {
$.ajax({
url: some_url,
data: some_data,
dataType: 'json',
success: function(data) {
items = data
}
});
result = items
}
// Playing with the 'result' variable...
The above code generates the error "items is not defined
" when some_condition
is false
(I think it happens because the variable scope is not correct).
I would like to set the result
variable to the AJAX response data but I don't know how to solve the problem.
Note: I am trying to do that because I would like to use the result
variable outside the if ... else
statement (that is, after the if ... else
statement in the above code).
Upvotes: 5
Views: 24997
Reputation: 398
Simply make the ajax function no async
var result = [];
if ( some_condition ) {
result = [...]
} else {
$.ajax({
url: some_url,
data: some_data,
dataType: 'json',
async: false,
success: function(data) {
items = data
}
});
result = items
}
Upvotes: 12
Reputation: 12693
Do this:
Since you are calling it async, you should assign it in your callback function
var result = [];
if ( some_condition ) {
result = [...]
} else {
$.ajax({
url: some_url,
data: some_data,
dataType: 'json',
success: function(data) {
result = data;
validateResult(result);
}
});
}
And for your better understanding.
Your result array is a global variable.
Upvotes: 3