Communicate Checkbox with Python

Asked

Viewed 142 times

0

I have a "checkbox" button with a JS event, the JS events are running normally, but I would like my JS code to run a file. py when checkbox is checked. How can I do this?

this is the html code

<div class="switch__container" >
    <input id="switch-shadow" class="switch switch--shadow" type="checkbox"name="field[]" value="1">
    <label for="switch-shadow"></label>
    <script src="js/teste.js"></script>
  </div>

this is the JS code:

var checkbox = $("#switch-shadow[type='checkbox']");

checkbox.change(function(event) {
    var checkbox = event.target;

    if (checkbox.checked) {
        setTimeout(function(){

            alert("Luz do quarto Acessa") 

        }, 1000);    
    } 

    else {
        setTimeout(function(){ 

            alert("Luz do quarto Desligado")

        }, 1000);  
    }

});

What’s more, my back-end is in python. That’s the code:

import RPi.GPIO as GPIO
import time
import cgi, cgitb

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(5)
print "LED off"
GPIO.output(18,GPIO.LOW)


  • Do you have a backend? In what language?

  • python, this is the python code: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18,GPIO. OUT) print "LED on" GPIO.output(18,GPIO. HIGH) time.Sleep(5) print "LED off" GPIO.output(18,GPIO. LOW)

  • It would not be the case to make an ajax when it selected the checkbox?

  • yes, exactly but I’m not getting to structure it on my JS

1 answer

0

To solve, just use the fetch to solve your problem as follows:

checkbox.change(function(event) {
    const checkbox = event.target;
    fetch(`http://www.example.com/?status=${checkbox.checked}`)
    .then(function(response) {
        alert(response.data);
    });

}

Then your backend would be in charge of altering the state of the light, based on what was sent to it through the GET and return whether it has been lit or erased and whether or not there has been an error.

  • Okay, I’ll test, and I’ll give you a feedback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.