I have 3 json requests which fetch data, i am wanting to store the results and add them together? i have made an attempt but i get NaN as they are getting set as null. What am i doing wrong?
var twitter, facebook, web, total_count;
// grab from facebook
var facebook = $.getJSON('https://graph.facebook.com/'+f_page+'?callback=?', function(data) {
var fb_count = data['likes'].toString();
fb_count = add_commas(fb_count);
$('#fb_count').html(fb_count);
});
// grab from twitter
var twitter = $.getJSON('http://api.twitter.com/1/users/show.json?screen_name='+t_page+'&callback=?', function(data) {
twit_count = data['followers_count'].toString();
twit_count = add_commas(twit_count);
$('#twitter_count').html(twit_count);
});
// grab from website
var web = $.getJSON('json.php', function(data) {
web_count = data['count'].toString();
web_count = add_commas(web_count);
$('#website_count').html(web_count);
});
$.when(facebook, twitter, web).done( countTotal );
function countTotal() {
total_count = facebook + twitter + web;
total_count = add_commas(total_count);
$('#count_total').html(total_count);
}
You are trying to acces data that is asychronously loaded. That means when the program code comes to this line:
The data isn’t there yet.
You need to wait until the data is ready:
PS:
Make sure total_count is defined somewhere as variable (var total_count), else it will pollute the global scope.