jQuery Storing Variables and Launching in DOM

Working on the quote generator here.

Here is the JS:

var quotesData ={}, currentQuote ="", currentAuthor ="";

  function getQuotes(){
return $.getJSON('https://raw.githubusercontent.com/themagicbean/bojackquotejson/master/bojackquotes')
.done(function(retrievedData) {
  console.log('got data');
  quotesData = retrievedData;
  //console.log(quotesData);
}).fail(function(error) {
  // Something wrong happened.  Like GOT Season 8.  JK didn't get past 6.
  console.error('We could not fetch or parse the data:', error);
});
}

function getRandomQuote() {
  return quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)];
}

function getQuote() {
  let randomQuote = getRandomQuote();
  currentQuote = randomQuote.quote;
  currentAuthor = randomQuote.author;
}

$(document).ready(function(){
  console.log("page loaded")
  getQuotes().then() => {getQuote()}; });
 console.log("post-functions")
  
  $("#new-quote").click(function (){
                          $("#quote-text").text("yomama");
                          $("#quote-author").text(currentAuthor);
                         console.log("clicked") });

})

Previously, my new-quote button seemed to work (i.e., before I moved other functions to within the DOM). Also, I know the getQuotes function works to pull the JSON (tried it out of the DOM) but it doesn’t seem to be storing/passing values. Admittedly, I’m not great at jQuery, but I’m having trouble understanding where things are going wrong. Can anyone give me a hand?

Hey,
there is alot going on in your code, and it not only jquery.

I’d offer you to clean up html and get read of styling until you fix functionality.
For example you got kinda pattern: div with id containing span with id containing text, whats the purpose of extra element? it doesnt do anything.
watch you brackets , curly brackets etc.
Ok , thats probably not something u wanted to hear.

You can’t store stuff from async requests, you can only use it where you received it ( e.g. display values from data in some div on a web page from within .done())
Like this

Hope this helps :slight_smile:

Ok , thats probably not something u wanted to hear.

True, but

You can’t store stuff from async requests, you can only use it where you received it ( e.g. display values from data in some div on a web page from within .done())

Was what I needed. But this has also left me a bit confused. If you look at the sample page for the quote generator here the jQuery, using AJAX, seems (to me) like it’s storing the async request data?

$(document).ready(function() {
  getQuotes().then(() => {
    getQuote();
  });

Where the functions are

function getQuotes() {
  return $.ajax({
    headers: {
      Accept: "application/json"
    },
    url: 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json',
    success: function(jsonQuotes) {
      if (typeof jsonQuotes === 'string') {
        quotesData = JSON.parse(jsonQuotes);
        console.log('quotesData');
        console.log(quotesData);
      }
    }
  });
}

And :

function getQuote() {

  let randomQuote = getRandomQuote();
  
  currentQuote = randomQuote.quote;
  currentAuthor = randomQuote.author;
...

(It also does a bunch of other stuff)

Is the arrow promise execution an exception to async data not being stored or … what is going on there?

Thanks!

1 Like

When i said that you cant store data, i meant you can’t just randomly create variable anywhere and assign you data to it,then operate or anything
As far as I can see, function getQuotes() returns ajax call, which returns promise object (not array), that is why in

$(document).ready(function() {
  getQuotes().then(() => {
    getQuote();
  });

we can chain .then() to it and data becomes accessible in getQuote() within .then() callback, and getQuote is putting things together to display in the app, generates random index etc.

@wanzulfikri

1 Like

Thank you! I’ve tried to integrate promises but I seem to be confused about how the objects are handled. Still working here.

JS:

$(document).ready(function(){
  let quoteText ="";
  let quoteAuthor = "";
  getQuotes().then((array) =>
                  {quoteText = array[0];
                  quoteAuthor = array[1]
                   console.log("then says "+ array);
                  })

Console isn’t logging “then says” and even if I try to pass the object directly (i.e., without specifying it’s an array), nothing seems to happen. Can you help me out here? I’ve spent a few hours on jQuery asynch tutorials but haven’t found the problem. Thanks!

Well done! you’re almost there
Hmm you don’t use promises or anything just because they exist, its a tool :slight_smile:
now just run you getQuotes function in $(document).ready(function(){}) to get the first quote,and inside your click handler to get another quote on click , and probably better rename it like getQuote.
Again : you dont need variables or then() in $(document).ready(function(){})

+dont think that nesting handlers is a good idea here. just saying

Here’s info abt promise chaining just in case you want to learn more

1 Like

Ah yes. I was trying to store the quote/author data in variables to then use those variables to fill in the tweet. But I don’t have to do that if I just use the jQuery selector when the tweet button is clicked. Working now!

1 Like