Home > database >  JSON API Button to toggle boolean
JSON API Button to toggle boolean

Time:01-19

im pretty new to json api and im trying to get a button for toggling a boolean value. This is the get request example.com/get/sonoff.0.Tasmota_BL.POWER it shows

{
  "val": true,
  "ack": true,
  "ts": 1442432238,
  "from": "system.adapter.admin.0",
  "lc": 1442431190,
  "expire": 28494,
  "_id": "system.adapter.admin.0.alive",
  "type": "state",
  "common": {
    "name": "admin.0.alive",
    "type": "boolean",
    "role": "indicator.state"
  },
  "native": {}
}

now i need a post(?) request to toggle val between true and false to this address: example.com/toggle/sonoff.0.Tasmota_BL.POWER

any ideas how to do this with a html button or js?

CodePudding user response:

To toggle the boolean value at the specified address using a HTML button and JavaScript, you can use the fetch() API to send a HTTP request to the endpoint. Here's an example of how you can do this:

<button id="toggle-button">Toggle</button>

.

let toggleButton = document.getElementById("toggle-button");

    toggleButton.addEventListener("click", function() {
      fetch("example.com/get/sonoff.0.Tasmota_BL.POWER")
        .then(response => response.json())
        .then(data => {
          let newValue = data.val === "true" ? "false" : "true";
          fetch("example.com/toggle/sonoff.0.Tasmota_BL.POWER", {
            method: "POST",
            body: JSON.stringify({ val: newValue })
          });
        });
    });

This code first gets the button element by its id, and then adds a click event listener to it. When the button is clicked, it sends a GET request to the "example.com/get/sonoff.0.Tasmota_BL.POWER" endpoint to get the current value of the boolean. It then uses this value to determine the new value that should be sent in the POST request. Finally, it sends a POST request to the "example.com/toggle/sonoff.0.Tasmota_BL.POWER" endpoint with the new value in the body of the request.

You may want to adjust the syntax and the endpoint based on the actual API you are using, and also check the API documentation for the required headers or any other information.

Also it's important to note that many APIs require authentication, so you will likely need to include an authentication token in the headers of your requests in order to successfully toggle the value.

  • Related