I am very new to PHP and working on a user interface. This is for a personal circuit breaker project where wattage and breaker status (ON/OFF) is sent to a database.
What I'm attempting now is to make a live status button for the interface. Essentially, I want the button class/background color to change according to the status row in the database. (Status = 0 --> Red status button, Status = 1 --> Green status button).
What I need help with is the automatic query of the database for the status value every 2-3 seconds. I know how to query for the value I want to read using mysql/php and how to toggle the button class/background color using a Javascript function.
Should I be using AJAX for is automation process?
Here is the module I am playing with: JSFIDDLE
Here is the most recent source:
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(this).toggleClass("off");
});
});
</script>
<style>
div{
float: left;
color:#fff;
font-size:40px;
}
h2{
text-align: center;
}
.wrapper{
position: absolute;
top: 25%;
left: 10%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
.one{
width: 125px;
height:100px;
}
.two{
width: 120px;
height:75px;
background:darkblue;
}
.three{
width:120px;
height:75px;
background:blue;
}
.button{
background-color: #4CAF50; /* Green */
border: 1px solid green;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
float: left;
position: relative;
left: 15%;
}
.button2{
background-color: #4CAF50; /* Green */
border: 1px solid green;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
float: left;
position: relative;
left: 15%;
}
.off {
background: red;
}
.button:hover {
background-color: #3e8e41;
}
.button2:hover {
background-color: #3e8e41;
}
</head>
</style>
<?php
$query ="SELECT status FROM ICBP.radio3 ORDER BY time DESC LIMIT 1;";
$result = mysql_query($query);
$status = mysql_fetch_row($result);
if($status = 0){
echo "off";
}
else if ($status = 1) {
echo "on";
}
?>
<body>
<h2>ICBP Dashboard</h2>
<div class="wrapper">
<div class="one">
<div class="two">
<a href="index3.php"><button class="button">Breaker 1</button></a>
<button class="button2">Status</button>
</div>
<div class="three">
<a href="index3.php"><button class="button">Breaker 2</button></a>
<button class="button2">Status</button>
</div>
</div>
<div class="one">
<div class="two">
<a href="index3.php"><button class="button">Breaker 3</button></a>
<button class="<?php echo $status ?>">Status</button>
</div>
<div class="three">
<a href="index3.php"><button class="button">Breaker 4</button></a>
</div>
</div>
</div>
</body>
</html>
Any guidance regarding my approach is very appreciated.
Thank you!