kkot
kkot

Reputation: 477

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!

Upvotes: 1

Views: 1039

Answers (2)

Jordan
Jordan

Reputation: 368

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.

Upvotes: 0

Axnyff
Axnyff

Reputation: 9964

This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.

Upvotes: 0

Related Questions