function calcula(item) {
var produtos_total = 0;
$.getJSON(url, {id: 1, ajax: 'true'}, function(j){
var options;
for (var i = 0; i < j.length; i++) {
options = j[i].valor;
}
produtos_total = options;
// alert(produtos_total); < - HERE PRINT
}); // JSON
alert(produtos_total); // HERE NOT :'(
}
Asked
Active
Viewed 44 times
-1

Paul Roub
- 36,322
- 27
- 84
- 93

dixavier27
- 66
- 8
-
1The function you supply to $.getJSON() runs when a response is received from the server, so this is where you need to handle it (ie, at the line `// alert(produtos_total); < - HERE PRINT`). Your second `alert()` executes before the server responds, while `produtos_total` is still 0. – Slippery Pete Aug 08 '14 at 20:16
1 Answers
1
Things are not happening in the order you think they are.
function calcula(item) {
// 1. start here
var produtos_total = 0;
// 2. set up an AJAX call
$.getJSON(url, {id: 1, ajax: 'true'}, function(j){
// 4. later, after the AJAX call completes
var options;
for (var i = 0; i < j.length; i++) {
options = j[i].valor;
}
produtos_total = options;
alert(produtos_total); // NOW we have a value
}); // JSON
// 3. leave the function
alert(produtos_total); // no value yet. AJAX hasn't completed
}

Paul Roub
- 36,322
- 27
- 84
- 93