Marcin Zalewski Marcin Zalewski - 2 months ago 17
Javascript Question

Getting random quote from JSON and appending it to div.

I'm trying to random quote which is in data.JSON file and append it to some div, but i'm getting error no matter where I put my variables:

My JS file:

$(specBut).click(function() {
var randomQuote;
$.getJSON('data.json',function(quotes){
randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
});
$('.quote').empty().append(randomQuote.quote);
$('.quote-author').empty().append(randomQuote.author);
});


And my data.JSON file:

{
"quotes":
[{
"author": "First author",
"quote": "First"
}, {
"author": "Second author",
"quote": "Second"
}, {
"author": "Third author",
"quote": "Third"
}, {
"author": "Last author",
"quote": "last one"
}]
}


I'm getting this error:


Uncaught TypeError: Cannot read property 'quote' of undefined


And that's how my HTML looks like:

<div class="quote-box">
<div class="head text-center"><h2>Random Quotes!</h2></div>
<div class="quote"> </div>
<div class="quote-author"></div>
<div class="buttons">
<a class="btn btn-default" id="specBut" href="#" role="button">New RQ</a>
</div>
</div>

Answer

The problem is $.getJSON('data.json',function(quotes){ here the quotes variable passed is the whole JSON doc which has another quotes key inside it. Which you can access by quotes.quotes. Also as the get method will be asynchronous,you need to perform all the operations inside the callback. So here is how it should be

$(specBut).click(function() {
    var randomQuote;
    $.getJSON('data.json',function(quotes){
        randomQuote = quotes.quotes[Math.floor(Math.random() * quotes.quotes.length)];
        $('.quote').empty().append(randomQuote.quote);
        $('.quote-author').empty().append(randomQuote.author);
    });

});