Random Quote Machine won't load quote on open

Random Quote Machine won't load quote on open
0

#1

I’ve built out my Random Code machine.

I have the $(document).ready call a function to load the API then place a random quote.

Only it doesn’t seem to work. the API loads but calling my function to load a random quote fails.

I’m perplexed.

Here is a link to my code…

I appreciate any help.

Thanks!


#2

I can’t replicate your problems. Clicking on a button generates a new random quote for me.


#3

The problem with you code is, the JSON response does not come back immediately. There is a small delay (though small) before it comes back. It is not until the response is loaded (req.onload), that there is actually data available. If you want to get a quote, you must do it inside the req.onload callback function. Because the XMLHttpRequest api is asynchronous, it does not wait for the response to come back and instead allows other code which can still run, to do so. Your getQuote function runs immediately after the loadQuotes function does, so it has no data at that point.