Is there a way to get the value of a select by PHP?

1

I'm trying to get the id of a product through a jQuery function, however I need to pass this variable to php, and since this snippet of PHP code is already within <script></script> it does not work the way I did below , then I would like to know if there is a way to get this value directly in the PHP snippet, or if there is another way to get this value. Remembering that I get the value only after selecting an option.

<select name="txt_os" id="txt_os" class="so">
    <option value="-1">Selecione uma opção</option>
    <?php
        while($linha = self::listar($qry))
        {
            echo "<option value=$linha[id]> $linha[titulo]</option>\n";
        }
    ?>
</select>


<script>
    var id = [];

    $(document).ready(function(){
        $(".so").change(function(){
            if (parseFloat($(this).val()) != -1)
            {
              id[0] = parseInt($(this).val());
              alert(id[0]);

              "<?php
                $idG = "<script>document.write(id[0])</script>";
                $sqlG = "SELECT * FROM gabinete WHERE id='$idG'";

                $g-> verDados($sqlG, 0);

                $precoG         = $g->getPreco();
              ?>"

              precoG = "<?php echo $precoG?>";
              alert(precoG);
            }
        })
    })
</script>

Exchanging

$idG = "<script>document.write(id[0])</script>";

by

$idG = "1";

It works normally, but I myself would determine the result, which is not the idea.

    
asked by anonymous 08.11.2014 / 00:06

1 answer

4

Mixing PHP with HTML though wrong is acceptable, now mixing PHP with JavaScript, 99% of the time is the worst match that can occur.

Separate everything as much as I could, and use AJAX. Something like this:

HTML

<select name="txt_os" id="txt_os" class="so">
    <option value="-1">Selecione uma opção</option>
    <?php
        while($linha = self::listar($qry))
        {
            echo "<option value=$linha[id]> $linha[titulo]</option>\n";
        }
    ?>
</select>

JS

$( document ).ready( function() {

    //var id = parseInt( $( this ).val() );

    var id = 123; // Valor fictício.

    $.get( 'getPreco.php', { 'id': id }, function( data ) {

        alert( data.preco );

    }, 'json' );
});

getPreco.php

<?php

// APENAS para facilitar o debug

error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', TRUE );

$idG = ( isset( $_GET['id'] ) ? $_GET['id'] : NULL );

if( is_null( $idG ) ) {
    // Erro: Sem ID
}

//$sqlG = "SELECT * FROM gabinete WHERE id='$idG'";

//$g-> verDados($sqlG, 0);

// Informação fictícia. Usando o ID passado como preço

header('Content-Type: application/json'); // Opcional

echo json_encode( array( 'preco' => $idG ) );
    
08.11.2014 / 01:19