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).
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).
2 Answers
Reset to default 12Simply 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
}
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.
- Initially its an array with length = 0;
- You call your ajax function.
- The length of result array is still 0.
- Ajax call completes and success function is executed.
- In success function you assign result to your response data.
- Now the length of result array is not zero any more .
- Globally the value is updated.
- You can use result array anywhere in your code
async: false
option for the$.ajax
makes it to work, but is theasync: false
deprecated? – user12882 Commented Nov 23, 2012 at 5:01