So I want to create an image that starts in a state based on a PHP function, and when clicked changes state.
I have not found any way to get the return value from a function in PHP to HTML. If I can do this, my problem is solved.
<?php
if(isset($_GET['button1'])){toggle();}
function toggle()
{
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r");
$value = fgets($f);
$newvalue = 1;
fclose($f);
if ((int)$value == 1) {
$newvalue = 0;
}
if ((int)$value == 0) {
$newvalue = 1;
}
$f = fopen($otherDirectory . $filename,"w+");
fwrite($f, $newvalue);
fclose($f);
}
function getLampState(){
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r");
$value = fgets($f);
return $value;
}
?>
<html><body>
<img src="lightbulb_1.png" onClick='location.href="?button1"'/>
</body></html>
Don't mind the toggle() function, I'm done with that. I have 2 files (lightbulb_1 and lightbulb_0). If getLampState() returns 1, I want to show lightbulb_1, vice versa.
Any advice?
Using JQuery...
$.ajax( {
type: "GET",
url: "phpScript.php",
success:function(data){
if(data==0)
$("#imgTagId").attr("src","lightbulb1.png");
else
$("#imgTagId").attr("src","lightbulb2.png");
}
});
In your php script simply "echo" whatever you wish to return.
If you're interested in including JQuery simply include the following anywhere in the head of your HTML:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
function doThings(){
$.ajax( {
type: "GET",
url: "script.php",
success:function(data){
//here whatever the script echos is inside "data"
if(data==0)
$("#imgId").attr("src","lightbulb_0.png"); //use # to select elements by id
else
$("#imgId").attr("src","lightbulb_1.png");
}
});
}
</script>
</head>
<body>
<!-- don't begin id's with numbers -->
<img id="imgId" src="lightbulb_0.png" onClick='doThings();'/>
</body>
</html>
script.php
<?php
//if(isset($_GET['button1'])){toggle();}
toggle();
function toggle()
{
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r");
$value = fgets($f);
$newvalue = 1;
fclose($f);
if ((int)$value == 1) {
$newvalue = 0;
}
if ((int)$value == 0) {
$newvalue = 1;
}
$f = fopen($otherDirectory . $filename,"w+");
fwrite($f, $newvalue);
fclose($f);
//this is what the html gets back (inside "data")
echo $newvalue;
}
//what's this function?
function getLampState(){
$filename = "brightness";
$otherDirectory="/sys/class/leds/led0/";
$f = fopen($otherDirectory . $filename,"r");
$value = fgets($f);
$filename = "lightbulb_";
$fileending = ".png";
echo $value;
}
?>
Does this work?