'how to show {"POWER":"ON"} in else if (this.responseText == ({"POWER":"ON"})) { [closed]

Hi all I am trying to get my page to change the button color when I have a response from this.responseText. I know the response I get from Json but I cant get it to allow the response in my code.

If someone could help me that would be great, I have been trying to get this working for sometime, or if you know of a better way to do that I am trying to do please let me know

<html>
    <head>
        <style>
            input.MyButton {
                width: 300px;
                padding: 25px;
                cursor: pointer;
                font-weight: bold;
                font-size: 150%;
                background: #3366cc;
                color: #fff;
                border: 1px solid white;
                border-radius: 10px;
                padding-bottom:25px;
            }
            input.MyButton:hover {
                color: #ffff00;
                background: #000;
                border: 1px solid #fff;
            }
            input.buttonStyle1 {
                 background: red; // or any color you wish
            }
            input.buttonStyle2 {
                 background: green; 
            }
        </style>
        <script type="text/javascript">
            function togglelight(ipstr) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        console.log(this.responseText); //To check output while error[Optional]
                        alert(this.responseText);
                        if (this.responseText == ({"POWER":"OFF"})) {
                            document.querySelector("input.MyButton").classList.add("buttonStyle1");
                        } else if (this.responseText == ({"POWER":"ON"})) {
                            document.querySelector("input.MyButton").classList.add("buttonStyle2");
                        }                 
                    }
                };
                xhttp.open("GET", "http://192.168.1."+ipstr+"/cm?cmnd=Power%20toggle", true);
                xhttp.send();
            }
        </script>
    </head>
    <body>
    <form>
        <br>
        <input class="MyButton" type="button" value="Office Light" onclick="togglelight('126')" />
        <br>
        <input class="MyButton" type="button" value="Fishtank Light" onclick="togglelight('128')" />
        <br>
        <label id ="officestatus">This</label>
    </form>
    </body>
</html>


Solution 1:[1]

You need to use JSON.parse() to convert responseText into an object, as follows:

var responseObj = JSON.parse(this.responseText);

if (responseObj.POWER === "OFF") {
   document.querySelector("input.MyButton").classList.add("buttonStyle1");
} else if (responseObj.POWER === "ON") {
   document.querySelector("input.MyButton").classList.add("buttonStyle2");   
}

Here follows a more complete example that uses id values on the buttons to toggle them On or Off individually.

It uses a simple helper StripState() to assess the status (On/Off) of the clicked button, which then allows us to simulate an AJAX response with the opposite state.

var suffix_on = " On";
var suffix_off = " Off";

function togglelight(ipstr) {
  var button = document.querySelector("#btn_" + ipstr); // get button by its id
  var isOn = StripState(button);
  
  this.responseText = '{ "POWER" : "' + (isOn ? "OFF" : "ON") + '" }';
  console.log(button.id + ' -> ' + this.responseText);
  var responseObj = JSON.parse(this.responseText);

  if (responseObj.POWER === "OFF") {
    button.classList.remove("buttonStyle2");
    button.classList.add("buttonStyle1");
    button.value += suffix_off;
  } else if (responseObj.POWER === "ON") {
    button.classList.remove("buttonStyle1");
    button.classList.add("buttonStyle2");
    button.value += suffix_on;
  }
}

function StripState(btn) {
  var isOn = btn.value.endsWith(suffix_on);
  var isOff = btn.value.endsWith(suffix_off);
  if (isOn || isOff) {
    btn.value = btn.value.substring(0, btn.value.lastIndexOf(' '));
  }
  isOn = !isOff; // in case it contained neither suffix
  return isOn;
}
input.buttonStyle1 { background: red;   }
input.buttonStyle2 { background: green; }
<input id="btn_126" type="button" value="Office Light" onclick="togglelight('126')" /><br>
<input id="btn_128" type="button" value="Fishtank Light" onclick="togglelight('128')" /><br>

Solution 2:[2]

Try this

if (JSON.parse(this.responseText)["POWER"] == "OFF") {
   document.querySelector("input.MyButton").classList.remove("buttonStyle2");
document.querySelector("input.MyButton").classList.add("buttonStyle1");
}
else if (JSON.parse(this.responseText)["POWER"] == "ON") {
  document.querySelector("input.MyButton").classList.remove("buttonStyle1");
document.querySelector("input.MyButton").classList.add("buttonStyle2");   
} 

If you want to toggle the color of multiple buttons using the same function, you can pass the reference of the button to the function and then add or remove it's class.

Below is the function

function togglelight(btn, ipstr) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if (JSON.parse(this.responseText)["POWER"] == "OFF") {
            btn.classList.remove("buttonStyle2");
            btn.classList.add("buttonStyle1");
        }
        else if (JSON.parse(this.responseText)["POWER"] == "ON") {
            btn.classList.remove("buttonStyle1");
            btn.classList.add("buttonStyle2");   
        }                
     }
  };
  xhttp.open("GET", "http://192.168.1."+ipstr+"/cm?cmnd=Power%20toggle", true);
  xhttp.send();
}

And HTML

<form>
    <br>
    <input class="MyButton" type="button" value="Office Light" onclick="togglelight(this, '126')" />
    <br>
    <input class="MyButton" type="button" value="Fishtank Light" onclick="togglelight(this, '128')" />
    <br>
    <label id ="officestatus">This</label>
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2