Search code examples
phpvariablesexecjscolor

Submitting jscolor result to shell_exec command


To start with: My web coding skills are nearly to non existent, I just did a bit of HTML ages ago... And my first steps with php are just made today.

My goal is: Having a color picker and sending the picked value as an argument to an python script.

I managed to use the jscolor picker libary (http://jscolor.com/examples/) and I've been also able to run the python scripts with an (color) argument from php.

My problem is now:

How do I submit the color string (hex-str) to the exec command (LED_color)?

<?php
    $LED_color="FFFFFF";

    $LED_color=escapeshellarg($LED_color);

    if (isset($_POST['button']))
    {
        $LED_color = $_REQUEST['hex-str'];
        echo shell_exec("sudo /home/pi/LEDscripts/color-by-arg.py $LED_color");
    }
?>


<html>
<head>
    <title>Basic usage</title>
</head>
<body>

<div style="position:absolute; left:280px; top:10px;">
    toString = <span id="hex-str"></span><br />
</div>


<script src="jscolor.js"></script>

Color: <input class="jscolor {closable:true,closeText:'Close me!',onFineChange:'update(this)'}" value="000000">

<script>
function update(picker) {
    document.getElementById('hex-str').innerHTML = picker.toString();
}
</script>

<form method="post">
    <p>
        <button name="button">Submit color</button>
    </p>
</form>

</body>
</html>

https://i.sstatic.net/1cXRn.png


Solution

  • Your color picker input needs a name attribute to match your PHP code, and also needs to be inside the <form> element.

    <?php
    if (!empty($_POST["hex-str"])) {
        $LED_color = escapeshellarg($_POST["hex-str"]);
        echo shell_exec("sudo /home/pi/LEDscripts/color-by-arg.py $LED_color");
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Basic usage</title>
        <script src="jscolor.js"></script>
    </head>
    <body>
        <form method="post">
            <p>
                Color:
                <input type="text" name="hex-str" value="000000" class="jscolor" data-jscolor="{closable:true,closeText:'Close me!',onFineChange:'update(this)'}"/>
                toString = <span id="hex-str-display"></span>
            </p>
            <p>
                <button type="submit">Submit color</button>
            </p>
        </form>
        <script>
            function update(picker) {
                document.getElementById('hex-str-display').innerHTML = picker.toString();
            }
        </script>
    </body>
    </html>