Home > Enterprise >  How do I run php code with a checkbox/slider
How do I run php code with a checkbox/slider

Time:02-01

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 >
            <div >
                <h1>Main Terminal</h1>
                <form action="index.php" method="post">
                    <label >
                        <input type="checkbox" name="checkbox_name" id="switch1" value="OFF" onclick=lights()></input>
                        <span ></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);
         }
        }

CodePudding user response:

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).

CodePudding user response:

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

  • Related