Quick question about FCC exercise Quote Generator

Hi, this is my first post in FCC Forums. I’m looking for advice about $(document).ready and $(window).load. My code in Code Pen works when the button is pressed to read a Mashape API and display the quote but doesn’t work when it’s first started. I tried adding a specific script element to the HTML instead of using just Code Pen settings but it still doesn’t work. Any advice would be great, this isn’t my first webpage as a programmer but it’s the first one that I’m writing in a Code Pen with jQuery.

Link to my Code Pen for this exercise: https://codepen.io/glennqhurd/pen/xPXgxM

It all looks pretty good, just one mistake. The two lines:

      $("#quote").html(currentQuote);
      $("#author").html(currentAuthor);

move them into the success method:

    success: function(r) {
      console.log(r)
      if (typeof r === 'string') {
       r = JSON.parse(r); 
      }
      currentQuote = r.quote;
      currentAuthor = r.author;
      $("#quote").html(currentQuote);
      $("#author").html(currentAuthor);
    }

should be inside your success function.

Remember that $.ajax is asynchronous. What is happening is that getQuote() gets called in the beginning. It makes the AJAX request. It doesn’t wait and continues on to the code and write the non existent quote and author to the screen (empty strings). Then a few milliseconds later, the AJAX call qets back and assigns a quote and author into those variables. Those don’t get written to the screen until the button is pressed, and then it writes that first quote to the screen while the second one loads. You’re always one quote behind.

Asynchronous behavior takes a while to get used to, but it is a great power of JS.

Thank you so much for the quick reply! This is definitely something I wouldn’t have found an answer to as quickly. I’ll make the changes immediately.

Cool, and also, you load jQuery twice, once the normal way (but incorrect for codepen) in the HTML pane and once “correctly” in the settings/javascript. You only need to load it once, and codepen wants you to do it in the settings.

Right, I was trying to troubleshoot my code and I thought maybe the problem was the declaration of jQuery. Once I got it working correctly I removed that line of code and it still works as intended. Also just now I added the Twitter and Tumblr buttons so I think I’m done with the assignment. Thanks again for the help, maybe someday in the near future I’ll be able to provide advice instead of asking it.

You’ll be surprised how fast you’ll be helping out others. We’re all on the same path and some of us are just a little farther along so we help those behind us. That’s the great thing about this group. Keep up the good work.

1 Like