JavaScript Triggering PHP Without Page Reload

24 07 2010

Same issue as in previous post JavaScript Triggering PHP but let’s do it without a page reload. This will necessitate revising the HTML, JavaScript and PHP that I presented in that last post.

The way to do this is by using a hidden frame, as follows:

<html>
<head><title>devshed exp</title>
<style>
iframe {
display:none;
width:100%;
height:33%;
}
</style>
</head>
<body>
<button id="mybut" accesskey="C">Click me</button>

<script src="devshed2.js" type="text/javascript"></script>
</body>
</html>

I made the iframe extra big so that if I need to do some var_dumping or see any error messages from XDebug I can view them after changing the iframe’s display to block. Note that the iframe lacks a src attribute. The JavaScript code below will take care of that by indicating a PHP file as a source and appending a query string to the URL, as follows:

var clrs = new Array('3333cc','9933ff'); // no #; only store hexcode values
var load = 0;
window.onload = function()
{
load++;
alert("Loaded: " + load);
ChangeColor();
}
document.getElementById("mybut").onclick = ChangeColor;
function ChangeColor()
{
var objIfrm = document.getElementById('ifr');
var dw = (objIfrm.contentWindow || objIfrm.contentDocument); // x-browser compliance
var bgc = dw.document.body.innerHTML;
if (bgc == "") bgc = 0;
document.getElementById("mybut").style.backgroundColor = "#" + clrs[bgc]; // hash optional
var target = "devshed2.php?bgcolor=" + escape(clrs[bgc]) + "&colors=" + clrs[0] + escape("|") + clrs[1];
document.getElementById("ifr").src=target;
}

The JavaScript code sets up an array of two colors and later supplies them to PHP in the querystring created in ColorChange(). Next I have a static variable load in order to demo that the page gets loaded only once. Then I set up some event handlers for when the page loads and the user clicks the button.

Both event handlers will invoke the ColorChange() which is what I’d call a proactive function. It gets the background color by fetching whatever value is in the iframe and changes the button’s background color. Then it changes the source of the iframe so that the PHP script is invoked and a new value now forms the content of the iframe. That way when the user clicks the button again, the updated value is there for the taking as this process starts over again.

Note: we don’t store the “#” in the colors array because this symbol indicates that a color should be set and all we want to do is just store the hexcode color values. With “style.backgroundColor”, using the “#” is optional, as with or without it, style.backgroundColor makes sure the background color gets set.

Now, let’s take a look at the PHP:

ob_start();
header("X-FRAME-OPTIONS: SAMEORIGIN"); 
class ClrChange {
     private $res;
	 public function __construct( $res ) {
	     $this->res = $res; 
	 }
	 public function toggleColor() {
	      return !$this->res;         // boolean
	 }
}
// START:
$bgc = "";
$strClrs = null;

if (isset($_GET['bgcolor'] )) {
	$bgc = htmlentities( $_GET['bgcolor'] );
}

if (isset($_GET['colors'] )) {
	$strClrs = htmlentities( $_GET['colors'] );
}

$clrs = array_flip( explode("|",$strClrs) );   // exp: pink => 0, lavender => 1

$o = new ClrChange( $clrs[$bgc] );
$res = (int) $o->toggleColor();      // cast boolean to int to see true/false as 1 and 0
echo $res;

The header in the PHP code above is supposed to help in connection with clickjacking. It basically tells the browser that it can trust this iframe and its content. After parsing the GET variables, these are used to set up an array that will be used by the ClrChange object $o to toggle the background color. I then echo the result which will be either a 0 or a 1 in the iframe for JavaScript’s subsequent use.

This work is licensed under a Creative Commons License
.

Advertisements

Actions

Information

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: