How do I make this function run every time I click a button?

For some reason I can’t get the code to format correctly, here is the codepen link (will put the code here later if it works):

Basically when I click “New quote” the quote doesn’t change, but if you paste this link (from the code) :[orderby]=rand&filter[posts_per_page]=1&callback=

You get a different quote every time you hit refresh.
If anyone has any ideas that would be greatly appreciated! :smile:


Here is the code:

function quoteGen(){
  $.getJSON("[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
  $("#qod-quote").replaceWith(a[0].content + "<p>&mdash; " + a[0].title + "</p>")

And here is the html for the button:

<button class="btn"id="quote-btn" onclick="quoteGen()">New Quote</button>

Hey, you might want to use html() instead of replaceWith(). Because if you execute the replaceWith the $("#qod-quote") is replaced, so on the next call of the function $("#qod-quote") doesnot exist anymore and can’t be replaced with the new quote.

The real “problem” is the fact that your requested is cached. So every time you make that request it will simply be fixed from the cache. To prevent this you can change $.ajaxSetup or change this line:
$.getJSON("[orderby]=rand&filter[posts_per_page]=1&random=" + Math.random() + "&callback=".
This makes sure that every request is unique and not fetched from the cache.

Hi, if you take a look to I think you will find some discussion about this issue, anyhow it seems that the browser calls the API only the first time and saves it in its cache. To prevent this behavior you should add to the url a timestamp +new Date().getTime(); this will make the url unique every time that you press the button, eluding your browser’s cache. I hope this could be helpful.

From jQuery docs:

The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call

Use html() instead. and the reason why it’s not changing is because ajax cache is on true by default for json unless otherwise specified.

      cache: false

either after or before, depends on your app. That way you can prevent it from being cached.

@BenGitter Wow thanks so much! Code works now, but just out of curiosity, doesn’t Math.random() choose a random number from 0 to 1?

Yes, it does. So, technically you could get two of the same numbers. But since it returns a number with so many decimals (e.g. 0.0500289405198695), this is very unlikely.

You could use anything as a parameter (name and value doesn’t matter) as long as they are different every time.

Oh ok, makes sense. Thanks!