How the Quotes On Design JavaScript API Works

Avatar of Chris Coyier
Chris Coyier on (Updated on )

I keep hesitating to call it an “API”, because I’m pretty sure this isn’t quite what “API” has come to mean. But, it is programming that interfaces with an application, so whatever. Last week I introduced the bit of JavaScript you can include on your page to add a random design quote to your page from Quotes on Design. Today, we’ll go over how it was built and how it works. Thanks again to David Walsh for helping me create it.

How does it work?

I really wanted to make sure that it was as easy as possible to use, which basically meant it had to be a “snippet”. It needed to be JavaScript for sure, as that gives us the power to alter the DOM and insert the quote as needed. At first, I went fully JavaScript. I had it read the sites RSS output and insert one of those at random. It turned out to be painfully slow, required a JavaScript library, and was limited to the last 10 quotes added.

David suggested making the JavaScript file actually a PHP file. Wha?

Tricky Tricky – The JavaScript is really PHP

Ultimately the JavaScript needs to really be JavaScript. But, we can gather the information we need first with PHP and then dynamically echo out what we need. You can see this in action if you load the JS file directly.

Make the server see it as PHP

First we need to make sure the server interprets the file as PHP, despite it’s .js file extension. We do this with a little HTAccess magic:

<FilesMatch "^.*?api.*?$">
SetHandler php-script
</FilesMatch>

I put this .htaccess file in the “api” directory on the server. Essentially it says that any file with “api” in it’s name should be interpreted as PHP. This will only work on Apache servers and will vary a bit from server to server. This is what worked for me on Media Temple (gs).

Make the browser see it as JavaScript

Our file, api.js, is now read to be interpreted as PHP on the server, we just need to make sure it’s still seen as JavaScript by the browser, so let’s make sure by putting this right at the top:

<?php
 
    header('Content-Type: text/javascript');

?>

The Desired JavaScript Output

Before we get started with the PHP, let’s take a look at what we ultimately need from the JavaScript. We need a simple function that uses the getElementById method to target our “quote” div and then use the innerHTML property to inject the quote in the proper markup.

function getQuote(id) { 
  document.getElementById(id).innerHTML = "<p class='qod-quote'>',QUOTE-GOES-HERE,'</p><p class='qod-author'><a href='',PERMALINK-GOES HERE,''>',AUTHOR-GOES-HERE,'</a></p>"; 
}

Don’t worry about the QUOTE-GOES-HERE business, that is what we’ll need the PHP for later. Then we need to call this function when the host site has loaded:

window.onload = getQuote("quote");

Getting the Data with PHP

Clearly we need to fill in the blanks in the function above with actual data. This is what we need the PHP for. The data resides in a WordPress database, so we need to connect to that database and then fashion a query to get what we need.

Connect to database

$link = mysql_connect('localhost','database_user','database_password');
mysql_select_db('database_name',$link);

Query for a random quote

The following will grab a single random entry from the database. Much of this is specific to a WordPress database, so we do special things like making sure the entry is published and is a post (as opposed to a page).

$query = 'SELECT post_content AS quote, post_title AS author, guid AS permalink FROM wp_posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY rand() LIMIT 1';
$result = mysql_query($query,$link) or die(mysql_error().': '.$query);

Turn result into an array

$row = mysql_fetch_assoc($result);

Inserting Data into Function

We already saw what we want the final JavaScript to look like, but now we can populate it with the proper data! Most of the data we can drop right in from our $result array, but the quote needs a little special cleaning up to account for special characters:

$quote = str_replace('"','"',$row['quote']);

And the final function, we can simple echo out:

echo 'function getQuote(id) { document.getElementById(id).innerHTML = "<p class='qod-quote'>',$quote,'</p><p class='qod-author'>',$row['author'],'</p>"; } window.onload = getQuote("quote");';

As you can see after we define the function, we call it during the window’s onload event, which triggers it when the page calling it is ready.

Do I have options?

Just one, if you really don’t want the permalink on there linking back to Quotes on Design, you can turn it off by appending a paramater (?link=no) to the URL. Yet another cool reason to use the PHP / JavaScript combo!

<script type="text/javascript" src="http://quotesondesign.com/api/api.js?link=no"></script>

This code should be fairly easy to adapt to add an “API” for almost any WordPress blog.