Is there something wrong with this API?

Hi everyone,

I’m a little confused at the moment i’m trying to use an api call to a random quote api but something is going wrong because I keep getting errors. I’ve tried every different possible way to call the api that I can think of and i’m stuck so if someone can help shed some light on this situation it will be greatly appreciated. I’m using jQuery by the way.

I’m probably gonna use a different api because I think something might be wrong with this one but I still would like to know why what I spent many hours on isn’t working.

If you wanna test at the code and try to fix it you can go here. I might change the code soon though but you can still copy the bottom code and paste it to try.


var quote;
var webUrl = "https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&callback=?&jsonp=parseQuote";

function getQuote() {
  return $.ajax({
    headers: {
      Accept: "application/json"
    },
    url: webUrl,
    dataType: "jsonp", // <== JSON-P request
    success: function onSuccess(jsonReturn){
                quote = JSON.parse(jsonReturn)
                console.log(quote);
             },
    error: console.log('broken')
});
}
  
$(document).ready(() => {
  getQuote();
  $('#text').text($(quote));
  $('#new-quote').on('click', getQuote);
});

Add this to your code and check console:

function parseQuote(data) {
  console.log(data)
}
1 Like

@jenovs OH MY GOODNESS! Who Are You, And What Is Your Name! because you literally solved my problem that I worked on for at least like 6 hours just confused with barely 3 lines of code.
Thank you so much!
If you don’t mind can you explain to me why that works the way it does I see that it’s a function that takes data as an argument and i’m assuming it when it runs it that argument becomes the json data from the api.

But

  1. why does that function run even without being called
    and
  2. how does the data argument automatically know it’s the information from the api.

Is the parseQuote a built-in JS function is data a built-in object sorry for all the questions but you just blew my mind :exploding_head:, and I want to know why. Thanks again!

It’s called JSONP - an old hack to bypass CORS.

If you’ll look at the url you’re fetching you’ll see the name of the function at the end. This is the name of the function you should create that will handle “returned” data.

Here’s detailed explanation about JSONP: https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms

I tried to use regular json at first but it wasn’t working so I used jsonp since I figured I had the best chance with that considering the domain is in russia somewhere lol.
But I didn’t realize that I had to use a special function or at least a function outside of the ajax call to get the data Thank you so much!