In this series I attempt to complete Free Code Camp as quickly as possible, without cutting too many corners. For an introduction to this series, see Free Code Camp #0: Speedrunning Free Code Camp.

In this entry I went through the JSON APIs and Ajax section, and made a small website that shows random quotes to a visitor.

First, I'm really lazy, so I didn't want to copy/paste a limited amount of quotes. Solution: A Quotes API. WikiQuite has an API, but the returned JSON is not structured at all. After searching around I found a great quotes API at Forismatic.com.

// http://api.forismatic.com/api/1.0/?format=json&method=getQuote&lang=en
{"quoteText":"A gem cannot be polished without friction, nor a man perfected without trials. ", 
"quoteAuthor":"Chinese Proverb", 
"senderName":"", 
"senderLink":"", 
"quoteLink":"http://forismatic.com/en/f3c3641b00/"}

Remember to use the JSONP URL, otherwise your browser will complain because of security reasons:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

The final code is short and concise:

var qurl = "http://api.forismatic.com/api/1.0/?format=jsonp&method=getQuote&jsonp=?&lang=en";
var turl = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
$("button").on("click", function() {
  getQuote();
});

function getQuote() {
  $.getJSON(qurl, function(response) {
    $("p").html(response.quoteText);
    $("i.author").html(response.quoteAuthor);
    $("#tweetlink").attr("href", 
      turl + response.quoteText + " ― " + response.quoteAuthor);
  }); 
}
getQuote();

The final result

Unfortunately the CodePen does not work when embedded on an HTTPS website. This is because the quotes API is HTTP-only, and web browsers disallow it for security reasons, so a screenshot will have to do. Try it on CodePen.

Things I've learned today:

  • Enabling HTTPS on your website has a lot of unforeseen problems.
  • display:flex allows crazy things and I still don't know anything.
  • U+2015 ‭ ― HORIZONTAL BAR is the correct dash to use between a quote and the author, according to the English Language StackExchange.
  • I can't believe we are still using JSONP. API authors everywhere should get with the times and enable CORS.

Next entry: Show the Local Weather