I’m no expert, but…
Yes, this is confusing, take a deep breath.
I would recommend spending some time on youtube. There are plenty of videos to explain some of these things.
In short, an API is just an “application programming interface” or a standard for how we can interface with a program, sever, etc.
Specifically to this project, we need an API that tells us how to interface with the forismatic server. Their server has a program running on it that when it is sent a specific string, it will send back a data packet. For example, if I send it https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?
, it will send back a quote
data package. You can test it now by opening a new window and putting that string in the address bar. This is sending back a json formatted package. Other formats exist, but json is what we’re using.
So, how do you get this into your Javascript program? AJAX comes to the rescue. It stands for “asynchronous JavaScript and XML” (XML is a different data format, but we’re using json). I find the AJAX command to be a little cumbersome, so I prefer to use JQuery’s function, $.getJSON. (Anytime you see the $ in front, you know that we’re dealing with JQuery.) It is JQuery’s way of doing an AJAX call. There are other ways to do this, but I find $.getJSON to be easier.
Here is the code:
url = "https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?";
$.getJSON(url, function(data){
console.log(data);
$("body").append("<p>" + data.quoteText + " - <i>" + data.quoteAuthor + "</i></p>");
$("body").append("<code>" + JSON.stringify(data, null, '<br/>') + "</code>");
});
You must have JQuery loaded for this to work.
The $.getJSON(url, function(data){
just tells JS to go out to server found at `https://api.forismatic.com’ and send it the string ‘api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?’ which the people have at Forismatic have set up to send back a random json packet with a quote. The url is just the string we defined earlier. The function(data) is an anonymous function we use as a callback to tell it what to do with the data we receive.
Note: All the code that uses data Must be inside (or at least called from inside) that getJSON function. It is AJAX so it is asynchronous meaning that JS will not wait for it to get the data (there will be a delay) so anything not inside that callback function will get run before that data comes back.