JSON only working once? Random Quote Generator

My current pen: https://codepen.io/drewgill89/pen/qxKbZm

$(document).ready(function() {
    var randomQuote, randomAuthor;
	
		function getQuote(){
		
			var url = "https://cors-anywhere.herokuapp.com/http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
			
			$.getJSON(url, function(data){
				randomQuote = data[0].content; //Is this possible?
				randomAuthor = data[0].title; //This as well?
				$(".quote").html('"'+data[0].content+'\"');
				$(".author").html("-"+data[0].title);
			});

		}
	$("#twitterBtn").on("click", function(){
window.open("https://twitter.com/intent/tweet?text=" + randomQuote + " " + randomAuthor);
	});
	
	$("#quoteBtn").on("click", function(){
		getQuote();
	});	
	
  });

I’m having trouble updating the quote/author every time the button is clicked, but I’m not sure why. Sometimes it will initially work after clicking the button 5-10 times, but then the quote/author will be stuck and not change despite clicking the button afterwards. There are also a few design issues with the location of the quotes, but that is not as important as the main functionality (I don’t think they’re connected). I’m not receiving any errors in the console.
Any advice is appreciated!

Have you confirmed that the getQuote() function is being entered every time the button is clicked? If so, is it possible that the service providing you quotes is throttling you?

$.getJSON is a preset case of using the $.ajax method, so you can not specify certain properties that some APIs require. The quotesbydesign API you are using caches the responses each time unless you tell it otherwise. To tell it not to cache the response, so you will get a new quote each time, you need to add the following code before your $.getJSON call.

$.ajaxSetup({cache:false});

Also, using the heroku proxy is slower than directly accessing the quotesbydesign API directly. If you want to access it directly, change your url to be:

https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
1 Like

Thank you! Worked nicely.