Random quote machine API does not pull random quotes

Hey guys,

My quote machine javascript keeps pulling the same quote over and over. When I refresh the API URL in my browser I see different quotes so I know the issue is in my code. Anyone see it?

var globals = {
  response: {},
  xhr: new XMLHttpRequest()
}

globals.xhr.addEventListener("readystatechange", reqListener, false) //listening for the readystatechange property to be changed

function new_quote_pull () {

  globals.xhr.open('GET', 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', true) //last value says "run this request async"
  globals.xhr.send()

  globals.xhr.onreadystatechange = reqListener // I don't understand line 14. I'd think reqListener should take an object (e) and then mutate it.

  reqListener()

}

function reqListener () {

  if (globals.xhr.readyState === 4 && globals.xhr.status === 200) {
    globals.response = JSON.parse(globals.xhr.responseText) //parsing turns a long string into an object

    // console.log(globals.response)

    update_quote_div()
  }
}

function update_quote_div() {
  // if (globals.xhr.readyState === 4 && globals.xhr.status === 200) {
  var quote_from_api = globals.response[0].content
  console.log(globals.response[0].content)
  console.log(quote_from_api)

  var quote_div = document.getElementById("quote-text")

  quote_div.innerHTML = quote_from_api
  // }
}

I don’t think it’s something with your code, I think it’s something with how the data is sorted on the backend when the API call is made.

For example, take a look at the Codepen “live example” on the API’s documentation page (https://codepen.io/chriscoyier/pen/MwaXpq?editors=0011), and notice that no matter how many times you refresh that page, the same quote is posted. If you fork that pen and change the filter[posts_per_page]=1 to another number like 2, and then keep refreshing that, you’ll notice the same 2 quotes always pop up.

That may be why in the documentation page’s “simple example” code (the full-blown ajax call), they have this line:
var post = data.shift();

Hope this helps

1 Like