0

I am working on project where I am trying to generate quote form api. Here is my syntax,

$("#btn").on("click",function(){
    $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",function(a){
   $("#display").append(a[0].content);
    })
 })

the problem I am facing is that I am not getting a new json return each time I am clicking the button, instead the same quote is generated. How can I fix that?

  • Inspect the response in your dev tools. Is it returning the same JSON each time? Is the browser caching it? – Damon Jun 10 '17 at 15:33
  • @Damon, could you please give me more insight on how to go about it? –  Jun 10 '17 at 15:39
  • What browser are you on? In most modern browsers you can right click - "Inspect" - and find a Network tab. Make your ajax request, and a new entry will show up with the request and response. What status code are you getting from the server? Is the response the same or different? If you are getting the same response each time and the status code is 200 (not cached), the problem is with the request itself (wrong syntax to get a random quote) or with the API itself. – Damon Jun 10 '17 at 15:43
  • Also, I just tried logging this request 3 times in my console (with no modifications) and it was different each time. jQuery automatically cache busts it so that wasn't a problem. – Damon Jun 10 '17 at 15:46
  • @Damon I am using google chrome. I just checked the network tab. Each time I am making request a new row is listed on the network tab. Its status code is 200(of course) and I hovered over size and it says from disk cache –  Jun 10 '17 at 15:49
  • Is there a cache buster param at the end of your Request URL? It would look something like `&_=1497109274251`. jQuery should do this automatically. – Damon Jun 10 '17 at 15:59
  • not really. The url at the network tab is just this 'posts?filter[orderby]=rand&filter[posts_per_page]=1' –  Jun 10 '17 at 16:02
  • can you post the exact URL under Headers > General > Request URL – Damon Jun 10 '17 at 16:07
  • @Damon thank you so much for all the support. I finally found myself way to set the caching false. –  Jun 10 '17 at 16:07
  • np, glad you figured it out. If caching was turned on, @nerestaren 's solution should have worked. – Damon Jun 10 '17 at 16:08

1 Answers1

0

That may be because your browser is caching the response.

I suggest you to add a timestamp to your request as a parameter, like

$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&t=" + new Date());

You can also check this question: How to set cache false for getJSON in JQuery?.

nerestaren
  • 156
  • 1
  • 12
  • Are you sure? [Your code](https://jsfiddle.net/fruh5ca7/) vs [my suggestion](https://jsfiddle.net/fruh5ca7/1/). – nerestaren Jun 10 '17 at 15:42
  • Thank you very. You are right. I set the cache false for getJSON directly and it worked –  Jun 10 '17 at 16:09