0

I have created a simple page the displays random quotes from QuotesOnDesign API. However, my "New Quote" element when clicked doesn't trigger the getQuote function. Here is a link to my code:

CodePen Random Quote

I suspect this is related to jQuery as the Chrome console displays an error mentioned that it refused to load script (referring to jQuery). The strange thing is that when I click on "New Quote" while I have the Developer Tools open in Chrome, it works!

5
  • i see no such errors (or any errors at all) in my developer console, although the button still seems to do nothing. Commented Jul 15, 2015 at 20:25
  • the event is triggering. i added console.log('test'); lines to the start of both functions and both caused output on the console when i click the button. Commented Jul 15, 2015 at 20:27
  • I think the browser is caching the response. Opening the console makes it work because you have the DevTools option to disable the cache when debugging. Commented Jul 15, 2015 at 20:42
  • Add a cachebuster to the URL. Commented Jul 15, 2015 at 20:42
  • thanks Woodrow. I also verified that the click event gets triggered. There must something off with the .getJSON call to the API. Any ideas? Commented Jul 15, 2015 at 20:43

2 Answers 2

3

The browser is caching the response the first time you call the API, and reusing that response on future calls. You can resolve this by adding a cachebuster to the URL.

The reason it works when you open the console is because you presumably have the Disable cache (while DevTools is open) option set.

function getQuote() {
  var cb = Math.round(new Date().getTime() / 1000);
  $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=" + cb, function(a) {
    $(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>");
  });
}

Working CodePen

Sign up to request clarification or add additional context in comments.

Comments

2

You can get rid of the funciton call altogether and give $.ajax a try like so:

$(".button").on("click", function(e) {
  e.preventDefault();
  $.ajax({
      url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
      success: function(a) {
        $(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>")
      },
      cache: false
   });
});

With cache: false you are preventing caching on a per call basis so the content changes each time the button is clicked as expected.

1 Comment

The important part is cache: false, you should mention that in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.