Search code examples
javascriptxmlhttprequest

JavaScript: How to "refresh" data from same URL?


Having this API: http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1

How can I write using pure JS request that downloads me different data after button click event?

All I get from this code is the same quote all the time:

function getQuote (cb) {
 var xmlhttp = new XMLHttpRequest();
 var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
 xmlhttp.onreadystatechange = function() {
    if (xmlhttp.status == 200 && this.readyState==4) {
        cb(this.responseText);
    } 
};
    xmlhttp.open("GET", quoteURL, true);
    xmlhttp.send();
}

document.querySelector('button').addEventListener("click", function() {
    getQuote(function(quote) {
        console.log(quote);
    });
})

I tried xmlhttp.abort() and stuff but it didnt want to cooperate. Thanks in advance!


Solution

  • Your response is being cached by the browser. A common trick to avoid this is to perform a request to

    http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
    

    Notice how the r={random_number} will make the URL different each time.