JavaScript Triggering PHP

23 07 2010

JavaScript (JS) needs to call PHP and have PHP return a value to JS which JS can use to toggle the background color.

JavaScript has come a long way since I first began using it circa 1997. People unaccustomed to the old ways, try to solve problems with XML-RPC or AJAX. But, what if you chose to ignore both of these methods, could the problem still be resolved? Yes, absolutely! Here is the code and note the clean separation of the JavaScript from the HTML, an MVC approach if you will.

<button id="mybut">Click me</button>
<script src="d.js" type="text/javascript"></script>

The contents of the javascript file are as follows:
window.onload = function()
var bgc = (blnRes == false)? 0 : 1;
document.getElementById("mybut").style.backgroundColor = clrs[bgc];
var bgc = (blnRes == false)? 0 : 1;
var target = "http://localhost/exp/d.php?bgcolor=" + clrs[bgc];
var clrs = new Array("pink","lavender");
var qs =;
var data = qs.substr(1,qs.length);
var blnRes = false;
blnRes = data.split("=")[1];

Note that the JS file is making use of anonymous functions and event handlers (see: What makes JS invoke PHP is the redirection achieved by using JS’s location object.

Okay, now let’s look at what happens to cause the PHP to execute. So JS redirects to a PHP script that looks like this:

class ClrChange {
     private $res;
	 public function __construct( $res ) {
	     $this->res = $res; 
	 public function toggleColor() {
	      return !$this->res; 
$clrs = array('pink'=>false, 'lavender'=>true);
$bgc = htmlentities( $_GET['bgcolor'] );
$o = new ClrChange( $clrs[$bgc] );
$res = (int) $o->toggleColor();
header("Location: http://localhost/exp/d.html?bgcolor=$res");

So, PHP has a class that is responsible for the color getting toggled. The actual color change is achieved after PHP redirects to the HTML page where a JS script parses the query string and determines which color to use for changing the button’s background color.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: