Loading...

Posts Tagged ‘HTML’

iPhone Home Controller v1 - PHP and AJAX Breakdown

Sunday, December 9th, 2007

Welcome, if this is your first time here, check out the full tutorial on controlling your home using the iPhone and x10. If you already have set up an x10 interface using your home PC, Apache and PHP, then read on for an easy PHP and AJAX breakdown of the code that drives the interface.

After many hours of playing around with the Activehome Pro CM15a interface and re-writing the code that makes it work on the web about 100 times, I have come up with a very simple few bits of code that anyone, running the CM15a with PHP, and Apache installed on their computer, can use to turn a device, or series of devices on or off with X10 and an iPhone or iTouch, or any web browser, or using the NIntendo Wii (which I do sometimes for shits and giggles). My main goal was to create a simple on/off button that worked without a page refresh. That required AJAX. Here is the simplest breakdown I have been able to come up with for all the necessary code. I am not going to post any CSS files this time but I will post my latest version, CSS and all, here soon!

The HTML:

<a href=”javascript:void(0);” name=”a1 on” id=”a1″ onclick=”lightUp(this.name)”>Turn A1 On/Off</a>
<div id=”response”></div>

The JavaScript:

var xmlHttp
function lightUp(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert (”Browser does not support HTTP Request”)
return
}
var url=”test.php”
url=url+”?q=”+str
url=url+”&sid=”+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open(”GET”,url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
{
var result= xmlHttp.responseText;
document.getElementById(’a1′).name = result;
var temp = new Array();
temp = result.split(’ ‘);
if (temp[1]==’off’){
document.getElementById(’response’).innerHTML = “you turned a1 0ff”;
}
else {
if (temp[1]==’on’){
document.getElementById(’response’).innerHTML = “you turned a1 0n”;
}
}
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}

The PHP (test.php):

$q=$_GET["q"];
$send = “ahcmd.exe sendplc”;
if ($q==’a1 on’){
exec(”$send $q”);
echo “a1 off”;
}
else {
exec(”$send a1 off”);
echo “a1 on”;
}

That’s it. Pretty simple huh? If you come up with anything that you would like to share please comment here.