I want to query a value from a script and use the value as variable for further functions. This code returns zero despite a value is set.
var total = 0;
var jqxhr = $.getJSON("number.php?jsonp=?", function(data) {
total = data[0]['Total']; // e.g 1234567
});
alert (total); // gives zero
I read that the problem could be with the asynchronous call and that my alert is executed before the anonymous function. I also tried to use some kind of setter function but withous success.
How can I set the global variable total
?
Edit:
I now tried to use deferred objects / promises. I still have the problem that I need the value from the AJAX call before I initialise my counter. I cannot create the counter object in the done
section because I cannot later change the value of the counter (still no global variable). Currently I have this:
var counter = $('.counter').jOdometer({
counterStart: '0',
numbersImage: '/img/jodometer-numbers-24pt.png',
widthNumber: 32,
heightNumber: 54,
spaceNumbers: 0,
offsetRight:-10,
speed:10000,
delayTime: 300,
maxDigits: 10,
});
function update_odometer() {
var jqxhr = $.getJSON("/number.php?jsonp=?")
.done(function(data){
console.log(data);
total = data['Total'];
counter.goToNumber(total);
})
.fail(function(data){
console.log(data);
});
};
update_odometer();
setInterval(update_odometer, 60000);
If I initialize the counter with zero then there is a strange start animations which jumps up and down. If I could get the real number instead of zero everything would work fine. Or should I completely switch to a synchronous call? How would I do that? Or are callbacks the better solution?