Coder1000
Coder1000

Reputation: 4461

Button JQuery event only working once, why?

<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/

Upvotes: 0

Views: 61

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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 + '"');
      }
  });
});

Upvotes: 2

Omar
Omar

Reputation: 527

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>

Upvotes: -1

Related Questions