Search code examples
javascriptjqueryaccess-control

Not able to fetch details at random order from API by using JSONP


There's this randomQuote API that I want to call using jQuery. When I call the API using the specified params in postman, I am getting random quotes on every click. But when I used jQuery in my webpage, I am getting a default quote and its not changing.
the objective is to fetch a random quote and display it on the web page whenever a user clicks on a button. I am using JSONP to bypass the Access-Control.

This is my query

 $(document).ready(function() {
  $("#click").each(function(index){
   $(this).on("click", function() {
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(key) {
	 $("#quote span").replaceWith(key[0].content + "<p>— " + key[0].title + "</p>");
         });
      });
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Please refer this link to know about the API https://quotesondesign.com/api-v4-0/


Solution

  • I figured out the solution.As it was said in the previous comments, a loop is not neccesary.

    $(document).ready(function() {
      var content="";
      $("#click").click(function() {
        $.getJSON("//quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(key) {
         content=key[0].content + "<p>— " + key[0].title + "</p>";
          $("#quote-form").html(content);
          console.log(content);
        });
        
        $("#quote-form").css({"font-family":"lucida console", "font-size": "20px","color":"rgb(255,255,150)"});
         
      });
     
    });

    The html method should be used instead of replaceWith. (Refer to the explanation of the previous answer of why replaceWith shouldn't be used here.