Nikolaos Alexiou
Nikolaos Alexiou

Reputation: 77

Issue with CodePen and jQuery

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!

Upvotes: 0

Views: 1298

Answers (2)

gffbss
gffbss

Reputation: 1701

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.

Upvotes: 2

Barmar
Barmar

Reputation: 781245

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

Upvotes: 3

Related Questions