0

the variable g's value is supposed to be passed to the percentage property BUT if I don't alert(g) before passing to percentage, it gives g's value as undefined. Gives an "Error in parsing value". language is js/jquery.

var g;     
function refreshCounts() {
    var url = 'https://graph.facebook.com/v2.8/?ids=' + postID + '&fields=' + reactions + '&access_token=' + access_token;
    $.getJSON(url, function(res){

        g = (defaultCount + res[postID].reactions_like.summary.total_count);

    });


}

$(document).ready(function(){

    setInterval(refreshCounts, refreshTime * 1000);
    refreshCounts();  
   alert(g);
    $('#jq').LineProgressbar({
        percentage:g,
        radius: '3px',
        height: '20px',
        });
});
Hanan Ur Rehman
  • 123
  • 1
  • 1
  • 8
  • You're stalling asynchronous execution with alert call (which is blocking and non-synchronous.) So, it is not the alert itself, but the fact that calling it gives your ajax call (getJSON) time to execute and set value of g. Without alert you are not blocking the ajax call & g is still undefined because your ajax call hasn't returned yet. – InfiniteStack Jun 23 '17 at 23:17

1 Answers1

1

The A in AJAX stands for Asynchronous.

In RefreshCounts, you launch an asynchronous call to populate g, which is set in a callback that is invoked when the AJAX request is complete. RefreshCounts then exits. At this point the callback may or may not have occured.

When alert is executed, it halts processing until the user accepts, giving the AJAX call time to complete (and populate g). Without the alert, processing moves immediately to the next line, and at that point g might not have been set yet.

To fix this, try:

var g;     
function refreshCounts() {
    var url = 'https://graph.facebook.com/v2.8/?ids=' + postID + '&fields=' + reactions + '&access_token=' + access_token;
    $.getJSON(url, function(res){

        g = (defaultCount + res[postID].reactions_like.summary.total_count);
        $('#jq').LineProgressbar({
            percentage:g,
            radius: '3px',
            height: '20px',
            });
    });
}

$(document).ready(function(){
    setInterval(refreshCounts, refreshTime * 1000);
    refreshCounts();  
});
John Wu
  • 50,556
  • 8
  • 44
  • 80