2

This is my first time posting to this site so I hope this is a good question. I've tried my best to google and watch videos but I cant seem to get my code to work as I am a novice with web dev as a whole.

So, basically I made a basic website that is meant to turn my lights on and off via an apache server on my Raspberry PI, however I cant seem to get the php code to execute when I use a slider/checkbox but when I use a normal button for 'on' and 'off' respectively the php code runs fine.

</head>
        <body>
        <center><h1>on or off... yes this is all it does</h1>
        <form method="get" action="index.php">
                <input type="submit" style = "font-size: 14 pt" value="OFF" name="off">
                <input type="submit" style = "font-size: 14 pt" value="ON" name="on">
                </form>
                        </centre>
<?php
        shell_exec("/usr/local/bin/gpio -g mode 17 out");
        if(isset($_GET['off']))
                {
                        echo "Light is off";
                        shell_exec("/usr/local/bin/gpio -g write 17 0");
                }
                        else if(isset($_GET['on']))
                        {
                                echo "Light is on";
                                shell_exec("/usr/local/bin/gpio -g write 17 1");
                        }

?>

This code runs fine and I can turn the lights on and off with no problems, however...

    <div class="column">
        <div class="main-switch">
            <h1>Main Terminal</h1>
            <form action="index.php" method="post">
                <label class="switch">
                    <input type="checkbox" name="checkbox_name" id="switch1" value="OFF" onclick=lights()></input>
                    <span class="slider"></span>
                </label>
            </form>

            <?php

            shell_exec("/usr/local/bin/gpio -g mode 17 out");
            if(isset($_POST['checkbox_name'])&& $_POST['checkbox_name']=='OFF')
            {
            echo "Light is off";
            shell_exec("/usr/local/bin/gpio -g write 17 0");
            }
            else
            {
            echo "Light is on";
            shell_exec("/usr/local/bin/gpio -g write 17 1");
            }
            ?>

This code does not seem to work at all.

It will always seem to default to the else statement regardless of the value of the checkbox. The onclick function I call is to change the checkbox value to ON and OFF respectively based on it's position and when I print it in the console these values are changing. I'm pretty sure it's the garbage php I wrote as I am a complete novice with websites as a whole.

As you can see I also tried a few things in the second portion of the code, I tried changing the method to post and using some other code I found online but it didn't work. I tried a lot other things like ajax query and other variations of the code above but they also did the same thing and didn't run.

I am aware it is my lackluster knowledge on php but after a lot of googling and videos I couldn't understand why it wasn't working. So if anybody could just help me in the right direction I'd appreciate it.

edit:Javascript code

        function lights(){
        var toggle = document.getElementById('switch1');
        if(toggle.checked){
        toggle.value="ON";
        console.log(toggle.value);
          }else{
        toggle.value="OFF";
        console.log(toggle.value);
         }
        }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Checkboxes won't do anything unless you tell them to, by either form submission (which the submit buttons do, but radio/checkboxes do not do), or catching the toggle with JS and triggering an AJAX request – Can O' Spam Jan 31 '23 at 14:04
  • Checkboxes / Sliders, doesn't "fire" a submit event, unless you tell it to. Also, post the code for the JS function `lights()` as it seems to be the firing function. – Anuga Jan 31 '23 at 14:05
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – DarkBee Jan 31 '23 at 14:06
  • Yeah, your lights function does nothing other than say "it's checked / unchecked" but does nothing with that information – Can O' Spam Jan 31 '23 at 14:09
  • @Anuga alright i posted the js function I have. I think thats where i am confused. how do I trigger a submit event without adding an awkward button? – Greg De Sousa Jan 31 '23 at 14:10
  • Add a name to your form (for example,`name="toggleLights"`) and trigger in JS; `document.toggleLights.submit()` - or use an ID on your form (e.g. `id="toggleLights"`) and use JS; `document.getElementById('toggleLights').submit()` – Can O' Spam Jan 31 '23 at 14:11
  • @Can O' Spam I did this and it seems to attempt something but it refreshes the page every time and makes my slider go back to the off state. And the lights still don't trigger. Is there a way i can trigger without it making the switch go immediately off – Greg De Sousa Jan 31 '23 at 14:19
  • Read about [AJAX](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started) - this should provide the answer you need without refresh – Can O' Spam Jan 31 '23 at 14:19
  • okay will do I already did try a ajax query but not thoroughly, I just thought there was a simpler way as the buttons worked fine, but I see it isn't as straightfoward. Thanks for the help – Greg De Sousa Jan 31 '23 at 14:25
  • You don't have to change the `.value` at all. That value is only sent when the checkbox is checked. So it doesn't send `OFF` it simply omits sending `ON`. – Peter Krebs Jan 31 '23 at 14:38
  • @PeterKrebs So are you saying that the value I put in the checkbox will only be set after it is checked and if it isnt checked it wont have a value? So if i set the value to "ON" initially it wont have a value, but when it's checked it will have the value "ON" ? – Greg De Sousa Jan 31 '23 at 14:48
  • You can `var_dump($_POST);` to see it. I have posted an answer with a possible workaround. – Peter Krebs Jan 31 '23 at 15:01

2 Answers2

1

Workaround using a hidden field

The value of the checkbox is sent only when the checkbox is checked. To force a default value being sent you can use a workaround where you use a hidden field with the same name, but having the "OFF" value:

<input type="hidden" name="checkbox_name" value="OFF"></input>
<input type="checkbox" name="checkbox_name" id="switch1" value="ON"></input>

If the checkbox remains unchecked the hidden value is used.
This works because POST requests which have multiple values for one name are processed so that the last given value is what $_POST will contain.
You build the form in a way that the hidden field comes first, give it the same name as the checkbox and validate the form accordingly.

Keep in mind you still have to validate since it is data coming from the browser, which cannot be trusted (someone can change the value of the hidden field using the browser's developer tools).

Peter Krebs
  • 3,831
  • 2
  • 15
  • 29
  • Okay that is quite smart, however I tried it and it still doesn't work. Do you think it is because I have to still submit it via an ajax request or something or is it because mabye my PHP statement is flawed to start with. – Greg De Sousa Jan 31 '23 at 15:21
  • If you send an AJAX request you can change the values to anything and it doesn't refresh the page so that looks nicer anyway. – Peter Krebs Feb 01 '23 at 08:18
1

Method using Ajax

update:

I got it to work! I had to scour the internet for a few hours but I managed to implement an ajax request in my javascript function which turns the lights on and off without refreshing the page

    function lights(){
            var toggle = document.getElementById('switch1');
            if(toggle.checked){
            toggle.value="1";
                      $.ajax({
                    type: "POST",
                    url: 'index.php',
                    data: {checkbox_name: $('input:checkbox:checked').val()}, 
                    success: function(data) {

                    },
                     error: function() {
                        alert('it broke');
                    },
                });

            console.log(toggle.value);
              }else{
            toggle.value="0";
              $.ajax({
                    type: "POST",
                    url: 'index.php',
                    data: {checkbox_name: $('input:checkbox:checked').val()}, 
                    success: function(data) {

                    },
                     error: function() {
                        alert('it broke');
                    },
                });

            console.log(toggle.value);
             }
            }

I changed the PHP abit too

      <?php
                $checkbox = intval($_POST['checkbox_name']);
                shell_exec("/usr/local/bin/gpio -g mode 17 out");
                if($checkbox==1)
                {
                echo "Light is on";
                shell_exec("/usr/local/bin/gpio -g write 17 1");
                }
                else
                {
                echo "Light is off";
                shell_exec("/usr/local/bin/gpio -g write 17 0");
                }
                ?>

I changed the values from a "ON" and "OFF" to a 0 and 1 but otherwise the rest of the code was the same