-1

So what I'm doing is getting values from a json file and pushing them to an array so that I can randomly select one and it is displayed in an html file. The problem i'm having is that even though something is in the array, it treats it as if it is empty...

var quotes = [];
var authors = [];

function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'quotes.json', true); 
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
        }
    };
    xobj.send(null);  
}

function init() {
    loadJSON(function(response) {
        // Parse JSON string into object
        var data = JSON.parse(response);
        for(var i in data){
            var key = i;
            var val = data[i];
            quotes.push(key);
            authors.push(val);
        }
    });
}

init();

var index = Math.floor(Math.random()* (quotes.length + 1));

document.getElementById("p1").innerHTML = "<span class=\"quotes\">&ldquo;</span>" + quotes[index] + "<span class=\"quotes\">&rdquo;</span>" + "<span id=\"author\">" + " – " + authors[index] + "</span";

So in my init function it pushes the key and the val to an array but it treats it like it's empty... i'm sorry if this is a simple question but i'm pretty new at JSON. Thanks

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Eric Leus
  • 57
  • 10

2 Answers2

0

I think your problem is that you're executing the last 2 lines of your code (those following the call to init function) before the work within the init actually completes.

In other words, pass a callback to init just like you did to loadJSON, then execute last 2 lines within.

Hari Lubovac
  • 106
  • 4
0

As pointed by Xufox you are dealing with async code, when getElementById runs your request for data has not finished yet, so you end up with an empty array for innerHTML.

This is not related to your question, but void to use for ... in as much as you can when dealing with arrays, prefer old school for for that or, if you are using Babel, for of.

Cleiton
  • 17,663
  • 13
  • 46
  • 59