Mixing JavaScript and PHP

March 8, 2008

This article is long overdue, but I’m glad to finally be talking about this topic. I recently designed a dynamic shopping cart. By “dynamic” I mean DHTML and Ajax-based with database-driven scalability (to some extent anyway). Take a test drive over here to see what I’m referring to.

Looking at the source, it looks like just a bunch of JavaScript. But you’ll also notice (if you aren’t crying yet by looking at the painful amount of code I had to write) that much of what you see looks redundant. Let’s take, for example, where I define some variables so that when you mouse over the ads, you can see more information.
// Variables for tooltip content
var ad1 = '<strong>iPod Touch</strong>Uploaded on 11/21/2007';
var ad2 = '<strong>iPod Nano</strong>Uploaded on 11/26/2007';
var ad3 = '<strong>iPhone</strong>Uploaded on 11/27/2007';
var ad4 = '<strong>Leopard</strong>Uploaded on 11/28/2007';
var ad5 = '<strong>Macbook</strong>Uploaded on 11/29/2007';
var ad6 = '<strong>iMac</strong>Uploaded on 11/30/2007';
var ad7 = '<strong>.Mac</strong>Uploaded on 11/31/2007';
var ad8 = '<strong>iLife</strong>Uploaded on 12/01/2007';
var ad9 = '<strong>iWork</strong>Uploaded on 12/02/2007';

A JavaScript declaration is required to make each floating tooltip work. But what if you want to drive the number of ads by what’s available in a database? This is where the beauty of mixing JavaScript and PHP comes in to play. The actual source of these repetitive variable declarations looks like this:
// Variables for tooltip content

$adtitle = array("iPod Touch","iPod Nano","iPhone","Leopard","Macbook","iMac",".Mac","iLife","iWork");
$adname = array("ad1","ad2","ad3","ad4","ad5","ad6","ad7","ad8","ad9");
$aduploaded = array("11/21/2007","11/26/2007","11/27/2007","11/28/2007",
//Total Number of Ads
$num = count($adtitle);
//Spit out the JavaScript?>
var <? echo"$adname[$i]"; ?> = '<strong><? echo"$adtitle[$i]"; ?></strong>Uploaded on <? echo"$aduploaded[$i]"; ?>';
<? } ?>

So this may look worse (and maybe it is) but it’s way cooler. I used those arrays you see up there because I wasn’t plugged in to their database, but if you know a little PHP, you can easily infer that database-driven data could fill those arrays up. So essentially this script says:

“How many ads do we have here? Okay, 9? Let’s run a loop and create 9 variable declarations and then go get some pizza.”

One of the trickiest things was to visualize what the end-result JavaScript syntax needed to be so that I could write the PHP accordingly. I had to “View Source” countless times until I got the script right.

Well, that’s one of my latest adventures of nerdery. That shopping cart has plenty of other chunks of complexity (it got much worse than declaring variables believe you me). It was pretty cool to actually complete, and a miracle to see operate correctly.