0

I am trying to get Comments stored in the Firebase using the below example. The script is looping through the json object and appending the HTML results to a global variable. However, the assignment in the loop does not append to the global variable.

var doccmnthtml = '';

try {
    $.getJSON( "https://ocw.firebaseio.com/.json", function( json ) {
        for (var key in json) {
            if (json.hasOwnProperty(key)) {

// Cannot append to the variable
                doccmnthtml += '<b>'+json[key].username+'</b><br/>'+json[key].text+'<br/><br/>';
            }
        }
    });
}
catch(err) {
    console.log(err.message);
}

alert(doccmnthtml);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Avinesh Kumar
  • 1,389
  • 2
  • 17
  • 26

2 Answers2

2

The alert is outside the ajax call, as it is async the variable is not getting assigned.

See the below code : I have included the alert inside the success call.

var doccmnthtml = '';

try {
  $.getJSON("https://ocw.firebaseio.com/.json", function(json) {
    for (var key in json) {
      if (json.hasOwnProperty(key)) {

        // Cannot append to the variable
        doccmnthtml += '<b>' + json[key].username + '</b><br/>' + json[key].text + '<br/><br/>';
      }
    }
    alert(doccmnthtml);
  });

} catch (err) {
  console.log(err.message);
}
Kishore Sahasranaman
  • 4,013
  • 3
  • 24
  • 50
0

The problem is that getJSON is an a-sync call which means that your alert is called before the response is set.

You can fix this by calling an callback function in the success-response.

Salmin Skenderovic
  • 1,750
  • 9
  • 22