0

I'm using a json api to create an array of data. For each item I want to create a html block to add to a list and append to a container. The following code works:

var url = "https://myjsonurl.json",

array = [],

html = "<ul class='card'>";

$.getJSON(url, function( res ) {
    array = res.badges;

    $.each(array, function(index, item) {
        html += "<li>HTMLblock</li>";
    });

    html += "</ul>";

    $("#reportCard").append(html);

});

However, the following code does not:

var url = "https://myjsonurl.json",

array = [],

html = "<ul class='card'>";

$.getJSON(url, function( res ) {
    array = res.badges;
});

$.each(array, function(index, item) {
    html += "<li>HTMLblock</li>";
});

html += "</ul>";

$("#reportCard").append(html);

This may be quite obvious but I can't understand why the last example will not work when the array and card variables are declared before the .getJSON call?

Bonobo
  • 11
  • 2
  • `https://myjsonurl.json` is no loaded and you are using it. simple. – Parth Trivedi Jan 02 '16 at 15:42
  • `$.getJSON` is asynchronous. You're using the array before it has finished. – Barmar Jan 02 '16 at 15:54
  • Is it not possible to save the response from the .getJSON call to a variable that can be accessed outside the callback function as I've tried to do in the second block of code? – Bonobo Jan 02 '16 at 15:54
  • It's certainly possible to use the variable outside the callback function. But it's not possible to use it *before* the callback has run, which is what you're trying to do. – Barmar Jan 02 '16 at 15:55

0 Answers0