Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a simple API call with jQuery getJSON

I am trying to build a simple Random Quote Generator in Codepen as you can see here: http://codepen.io/scabbyjoe/pen/dXQmLw

Relevant code pasted below:

<html>
    <head>
    </head>
    <body>
        <h1>Random Quote Machine</h1>
        <div class="quote">
        </div>
        <div class="btn">New Quote</div>
    </body>
</html>

$(document).ready(function() {
    $(".btn").on("click", function(){
        $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
            $(".quote").html(JSON.stringify(json));
        });
    });
});

I am afraid I must be misunderstanding the getJSON tool as I cannot get any content to load up in my .quote div.

Can anyone explain why this isn't working?


I am try to follow from this (separate) example which is indeed working:

<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function(){
      $.getJSON("/json/cats.json", function(json) {
        $(".message").html(JSON.stringify(json));
      });

    });

  });
</script>

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>
like image 873
scabbyjoe Avatar asked Feb 06 '23 10:02

scabbyjoe


2 Answers

Your can discover the error message in console panel:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

You should make sure the api.forismatic.com serve the resource with cross domain allowed.

Or you could take a look of jquery.ajax crossDomain option


like image 37
Radian Jheng Avatar answered Feb 09 '23 00:02

Radian Jheng


Check your console for errors:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

You cannot make AJAX requests to a service hosted on a domain separate from your own unless they specifically allow it. This message indicates that it is not allowed.

Perhaps it's allowed in certain circumstances; check their documentation. If it's not, you'll have to proxy the request through your own server. There's no guarantee it's allowed in that situation either. You may have to provide them something like an API key or get added to a whitelist.

like image 157
Jacob Avatar answered Feb 08 '23 22:02

Jacob