Fortune Cookies

→ JavaScript vs. PHP ←

Try PHP
PHP App
PHP Code
PHP Code
Try JavaScript
JS App
JavaScript Code
JS Code
Try Ajax
Ajax App
Ajax Code
Ajax Code

It is a hacker tradition to write a program that shows a random proverb or fortune. This goes back to the day of UNIX terminals that would run programs automatically upon login. You could set up your terminal to show you a random funny, motivational, sarcastic, or inspirational thought. We did this back in my days at UC Santa Cruz in the early 1990s.

Not so many people log into UNIX terminals daily like this now, although, to be honest, I'm currently logged into the Mac Terminal program and I'm typing this code in vi, my favorite text editor. So if I had the fortune program installed, I could run it. Instead, we'll display the fortune on a web page. It could be at the bottom of your personal home page, or it could be a separate page set apart for the purpose of only displaying a fortune.

A random fortune program consists of two parts: (1) a database of sayings, and (2) a program that chooses one saying at random to display on the screen. The program is actually pretty simple. The database can range from a dozen sayings to literally thousands.

We make this program in my PHP course at Mission College and also in the JavaScript portion of my Mobile App Design course at Silicon Valley CTE (high school). We could code this in any language, but what are the tradeoffs?

PHP

Try PHP
PHP App

JavaScript

Try JavaScript
JS App

AJAX

Try Ajax
Ajax App

Ajax (Asynchronous JavaScript with XML), if implemented correctly, can combine the best features of both PHP and JavaScript. With Ajax, we make the front-end (display and user interaction) using JavaScript, but we make the back-end (database) with PHP. When the user requests a new fortune, we request one from the server, and we transfer only the new fortune, not the whole page.