0
<script>
        $("button").on("click", function() {
            $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(json) {
                $(".author").html(json[0].title);
                $(".quote").html('"'+json[0].content+'"');
            });
        });

    </script>

Situation: I click, the data is loaded. I click again, nothing changes.

Codepen: http://codepen.io/anon/pen/vxGgaZ

Reference: https://quotesondesign.com/api-v4-0/

15
  • Any errors in the console? Obviously visibly nothing will happen after the first getJSON call because you have already rendered the html the first time. If the request is not firing the second time then you need to check for errors. Commented Mar 2, 2017 at 21:16
  • Are you sure the data on the server is changing between clicks? Commented Mar 2, 2017 at 21:17
  • Is the button a child element of .author and/or .quote? If so you have to use event-delegation for it to work Commented Mar 2, 2017 at 21:18
  • @empiric not a child. Commented Mar 2, 2017 at 21:18
  • 1
    @CamJohnson26 you can check by yourself with the url. It changes. Commented Mar 2, 2017 at 21:18

2 Answers 2

2

The problem is because the first response is being cached. You can solve that by adding a $.ajaxSetup() call which stops the caching:

$.ajaxSetup({
  cache: false
})

Updated Codepen

Alternatively, use $.ajax() and set cache directly in the settings:

$("button").on("click", function() {
  $.ajax({  
      url: 'http://quotesondesign.com/wp-json/posts',
      type: 'get',
      cache: false,
      data: 'filter[orderby]=rand&filter[posts_per_page]=1', 
      success: function(json) {
        $(".author").html(json[0].title);
        $(".quote").html('"' + json[0].content + '"');
      }
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

That's what I was searching for, couldn't remember the exact code for this
Is resource served with CORS headers?
@RoryMcCrossan Still have not found a way to navigate codepen interface. stacksnippets uses http://null as origin, though was able to get resource using <link> element at plnkr. Note ); following success at javascript at Question.
-1

Try Like This:

Maybe it's help you

<script>
        $(document.body).on("click", 'button', function() {
            $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(json) {
                $(".author").html(json[0].title);
                $(".quote").html('"'+json[0].content+'"');
            });
        });

    </script>

1 Comment

Did not change anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.