See if a checkbox was selected in PHP

1

I want to validate and execute PHP code depending on whether you click checkbox or not. In the form this this:

<input type="checkbox" name="checkbox" value="marcado">
<input type="submit" name="">

And in PHP I have:

if (!empty($_POST['checkbox'])) {
    echo "MARCADO";
    echo "<br/>";
    echo $_POST['checkbox'];
} else {
    echo "ERROR";
    echo "<br/>";
    echo $_POST['checkbox'];
}

But it always shows the ERROR message, whether or not you click checkbox .

    
asked by Piropeator 12.07.2018 в 22:44
source

2 answers

2

Is it necessary to use PHP? A very simple way to do it is to use jQuery, so that it is an AJAX that takes care of such a request. For this it would be necessary to add an id to the checkbox:

<input id="cbx1" type="checkbox" name="checkbox1" value="marcado">
<input type="submit" name="">

And the jQuery in question:

$(document).ready(function() {
   $("#cbx1").click(function() {
       if ($(this).is(":checked")){
         doChecked(); // Función si se checkea
       } else {
         doNotChecked(); //Función si no
       }
   });
});
    
answered by 12.07.2018 / 22:57
source
1
if (isset($_POST["checkbox1"])) {
   echo $_POST["checkbox1"];
} else {
   echo "error";
}
    
answered by 12.07.2018 в 22:57