Changing a variable’s value with a PHP check box

Asked

Viewed 1,260 times

0

When I click on the option I wanted to send by get, a value. Type something like this

    <form action='_cal.php?change=1' method="get">
        <input type="checkbox" name="change" value="change">Alterar<br>
    </form>

and receive in PHP

$change=(isset($_GET['change']) ? $_GET['change'] : '0');

With you with a link, I now wanted to change for a checkbox.

  • How the form is being sent?

  • By GET. I want to send to the same page.

  • So just change the value="change" for value="1"on the line of input and take out the ?change=1 of the line of form.

  • 2

    Note that these variable change questions do not make much sense, since, with the default architecture, it is not possible to change anything that is done in PHP through an HTML or JS/Ajax. What is happening is the sending of new information. When an HTML or JS is running, the PHP that generated them has already been processed and is already "running". You will always be calling a new PHP execution, be it the same script or another.

  • Try by AJAX , making an asynchronous request , of a researcher on this subject , will be of great use

  • 1

    It would be possible for you to rewrite your question in more detail and stating exactly what you want to do?

Show 1 more comment

2 answers

1

Essentially what you’re looking for is to submit the form when someone clicks on checkbox instead of using links.

For this purpose, you can add an attribute onChange to the element checkbox that will run Javascript responsible for triggering the submission of the form:

<form action='_cal.php' method="get">
    <input type="checkbox" name="change" value="1" onChange="this.form.submit()"> Alterar
</form>

Note that I also changed the address of the form because by submitting the same route GET, will be added to the URL a string in format NVP of the fields present in it.

Your checkbox is called change and with the value 1, in combination with the URL _cal.php where the form will submit the information, you will get:

_cal.php?change=1

Additional note:

To check the presence of the URL variable change, you can simplify your code to:

$change = (int)isset($_GET['change']);

To explain, the function isset() returns a boolean TRUE or FALSE. Preceded by (int) will pass the boolean to its numerical representation 1 or 0.

See demonstration in Ideone.

0

Here is the code of the index.php page I did for testing, I used only php, html and jquery:

<?php
    // Código php pra dar a resposta do ajax
    // Se o get for setado (se o checkbox for marcado)
   if (isset($_GET["change"])) { 
        // Imprime o get (no caso, retorna o valor pra nossa variável data
        echo $_GET["change"];

        // Dá o exit, 
        // pois aqui na minha máquina ele estava retornado o código fonte de toda
        // a página html
        exit();
   } 
?>
<html>
    <head>
        <title>Teste get</title>
    </head>
    <body>
        <form action='index.php' method="get" id="form">
            <input type="checkbox" name="change" value="1" id="change">Alterar<br>
        </form>

        <div id="resultado" style="margin: 20px auto; width: 300px"></div>

        <script src="jquery.js"></script>
        <script>
            $(document).ready(function() {

                // Evento JQuery que captura as mudanças do checkbox - pode ser substituído pelo click()
                $('#change').change(function() {

                    // Se o checkbox estiver :checked
                    if ( this.checked ) {

                        // Guarda o value do input numa variável
                        var chkData = $('#change').val();

                        // Inicia evento ajax, aqui é basicamente a resposta que você procura
                        $.ajax({
                            url: $('#form').attr("action") + "?" + $('#form').serialize(),  // Pega a URL no formato do get
                            type: 'GET',    // Define o tipo do submit
                            data: chkData,  // Aplica o valor do checkbox à variável data

                            // Caso o request termine em sucesso, mostra o resultado recebido na div#resultado
                            success: function(data) {
                                $("#resultado").html("Funcionou!!<br />" + data);
                            },
                            error: function(e) {
                                console.log(e.message);
                            }
                        }); 
                    }
                });
            });
        </script>
    </body>
</html>
  • 2

    I know the author’s question is not so clear, but his answer is even less so. Consider giving more details, such as what language you are using, what framework etc...

Browser other questions tagged

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