Random Quote Machine project AJAX problem

Hi guys, I’m having a problem with AJAX (maybe, could be something else) with my Random Quote Machine project. I actually finished the project a few months ago and I used jQuery. A few days ago I decided to replace the jQuery with just plan JavaScript. It seemed to be working fine until I realised that for some reason it only works when I have the JavaScript console open (Chrome). I don’t know how or why this is happening but I can’t seem it figure it out.

With the console closed, when I click on the “New Quote” button, nothing happens at all but when I do open the console and click the button, it generates a new quote just fine. I added a line to show the readystate if it’s not 4 and it seems to do 1, 2 and 3 (which is loading) but it never seems to get to 4 unless the console is open. It’s so weird. I also tried Firefox and that doesn’t work at all, even with the console open. However I did notice that it makes requests to the API (and successfully receives new quotes) but it does so constantly (almost like an infinite loop) until I close the tab. But the quote displayed in the document never changes.

You can have a look at my code here: https://codepen.io/ntjnh/pen/QabKNO

If anyone can help me to figure this out, I’d be grateful :slight_smile:

This topic can be closed. I figured out the problem.

Just in case anyone ever has an issue like this:

In my jQuery version, I had this line of code:

$.ajaxSetup({cache: false});

I suspected my problem was related to this so I tried to find the plain JavaScript way of disabling caching and I found this article: A Guide to Vanilla Ajax Without jQuery It’s the section right at the end under “Cache Busting”. I added these lines to my code:

const bustCache = '?' + new Date().getTime();
const quoteUrl = "//quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
quotes.open("GET", quoteUrl + bustCache, true);

It works now! (I tried it on Chrome, Firefox and Safari just to be sure) and I’m so relieved because I was trying to figure this out for like 2 days. :laughing:

1 Like