Aim: User clicks a button it retrieves latest record of json from database and updates state of green led to 1
Here whats I have so far, all code in one file index.php
The php code
$sql = "SELECT json FROM `smartlight` ORDER BY timestamp desc limit 1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
Then html
<a href="#" class="btn btn-default" onclick="myFunction()">More Options</a>
Then javascript
<script type="text/javascript">
function myFunction(){
var emparray = <?php echo json_encode($emparray) ?>;
console.log ( emparray );
for (var i=0; i<emparray.length; i++) {
if (emparray[i].device == "greenled") {
emparray[i].state= "1";
break;
}
}
console.log ( emparray );
}
</script>
Both console.log produces the same thing...
"{"smartdevices":[{"device":"greenled", "state":"0"},{"device":"redled", "state":"1"}]}"
Is it because in my javascript im trying to loop through something that isn't yet in the right state to be looped like this?
Thanks in advance
The content from your database is a string. You need to decode the string first so your entire PHP array is evaluated when you run json_encode
.
First, alter your PHP code like this:
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
// Decode the string here
$emparray[] = json_decode($row['json']);
}
You now need to loop the outer array, then the code inside.
Something like this:
// Loop the outer array (each part of $row)
for (var i = 0; i < emparray.length; i++) {
// Loop each part of the 'smartdevices' array
for (var j = 0; j < emparray[i]['smartdevices'].length; j++) {
if (emparray[i]['smartdevices'][j]['device'] == "greenled") {
emparray[i]['smartdevices'][j]['state'] = "1";
break;
}
}
}