2

Hello I am trying to make quote generating machine and I am reading quotes from forismatic api and it getQuote method. I am new to this and I have tried .getJSON and .get method but I always get error. Can someone please tell me what am I doing wrong in reading from server? Once I have read it how to I put it onto html and how do I debug in such situations. So far I have done this

JS file

$("document").ready(function() {
    var request = $.ajax({
        url: "http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=xml&lang=en?",
        method: "GET",
        dataType: "json"
    });

    request.done(function(msg) {
        $("#log").html(msg);
    });

    request.fail(function(jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

HTML file

<head>
  <title>Random Quote Machine</title>
</head>
<body>
  <div class="jumbotron">
    <div class="container-fluid">
      <div class="page-header text-center">        

        <h1>Random Quote Machine</h1>
        <p class="result bg-primary">Quote Goes here</p>
        <button class="btn btn-primary type="button">Generate Quote</button>
      </div>
    </div>
  </div>
</body>

thanks and sorry if i did something wrong

Milap
  • 6,915
  • 8
  • 26
  • 46
mojo jojo
  • 21
  • 2

2 Answers2

0

try to remove Last "?" from URL

this should be

url: "http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=xml&lang=en"

Jatin Bhole
  • 176
  • 7
0

The reason you are getting an error is because you are trying to do a cross origin AJAX call. CORS(Cross Origin Resource Sharing) is not allowed in JSON AJAX requests. So the solution is JSONP.

JSONP - JSON with padding, is commonly used to bypass the cross-domain policies.JSONP uses a callback function for response. for more info read this explanation.

Here's how you can get API response from forismatic via JSONP request.

function parseQuote(response) {
 console.log(response);
 $("#quote").text(response.quoteText);
  $("#author").text(response.quoteAuthor);
};
var tag = document.createElement("script");
tag.src="http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=parseQuote";
$('#quote').html(tag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='quote'></p>
<p id='author'></p>
Community
  • 1
  • 1
Roh777
  • 1
  • 1
  • 1