Is there any way to get the "value" of a "select" from PHP?

Asked

Viewed 951 times

1

I’m trying to catch the id of a product through a jQuery function, but I need to pass this variable to php, and as this chunk of PHP code is already inside the <script></script> does not work the way I did below, so 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>";

for

$idG = "1";

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

  • Shows the id that is in the option selected in the first, in the second the result is empty.

  • But what second?

  • @Brunoaugusto has two Alert in the code, Alert(id[0]); and Alert(Precog);

  • The problem is this Document.write(). Since PHP is embedded in Javascript, after the equal sign of $idG you close double quotes, concatenate with the plus sign (+) put the normal JS variable, concatenate again and reopen double quotes

  • @This would look like this: "<? php $idG = " + id[0] + "; $sqlG .... ? If it didn’t work.

1 answer

4


Mixing PHP with HTML although wrong is acceptable, now mixing PHP with Javascript, 99% of the time is the worst union that can occur.

Separate everything, as much as possible, 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 ) );
  • Thanks for the help, but I did this way and the value returned was as "Undefined", would tell me some reason for it to happen?

  • That’s why I said something like that. It is not for you to copy, paste and hope that it works. What I did was simply separate what you already had in a more logical way. I modified a few things but who will tell if it’s right or not you. If you received a Undefined in JS, the error is in getPreco.php. Access this file and pass a GET parameter (getPreco.php?id=123) and see if an error appears in the browser. If it appears, correct. If it does not appear check that the json generated by json_encode() is in accordance with what the JS is using.

  • i had already tested several ways, just not passing the id this way: (getPreco.php?id=1). i have not modified anything in getPreco.php code and what is shown on screen is this, {"price":"199.99"}, exactly what I should present

  • I did another test, I replaced json_encode for just that echo $g->getPreco(), and it worked, but I need the array, I had a similar problem in another code that I solved with this 'header('Content-type: application/json');', but putting this not the return any

  • If you saw {"preco":"199.99"} is a good sign, JSON is being generated correctly. You have received a Undefined in Javascript then the error is only in it. Take a look at what the variable Precog Javascript is being populated and what you have in your JSON.

  • I’m sorry, but I didn’t understand what you meant by "Javascript’s Precog variable is being populated", and how do I see what I have in JSON? : P

  • By accessing the URL manually or by opening the Browser Console, click on the request made to getPreco.php and seeing what it says in the Reply tab. You had tried to use a PHP variable called $Precog. When I rewrote I built JSON the same way and the Javascript variable Precog was being populated with the index Precog return JSON. Your output shows an index price and not Precog. How you just copied, generated a Undefined because there is no index Precog in your JSON.

  • actually I didn’t copy 100%, I got what I needed, and I traded Precog for the price, both in getPreco.php and in the main code.

  • It remains to record what date has then. Within that $.get function put console.log(data) and see what appears on the console. And whoever it was who denied the reply without comment or try to help, thank you.

  • I put the console.log(data), and what appears is this:{"price":"299"} but if you put console.log(date.preco) it is Undefined

  • Ô Zica... I was sure the code was correct, but because I ended up trusting jQuery’s "intelligence" in guessing the types of data in transit, I assumed the argument date available in the successful callback would be a valid JSON. But apparently it turned out that it was a flat text and so did not work. Force the return type for json as per the edit I made in the reply and it will work.

  • Zica SAME... I made the modification and now is no longer entering the ajax function :/

  • Take a look, you must have done something more or less, because I tested it (not with database information, of course) and it worked. I reviewed the JS and PHP and edited to chew the solution more.

  • it took me a while to get back, but then, I did a thousand and one revisions and I couldn’t find anything wrong, but if changing the JSON request to HTML works (of course, apart from the return array), json doesn’t enter the sucsses function.

  • Post what you have in a Jsfiddle, edit the original response with the link to the updated version. Even if Jsfiddle won’t run PHP it’s just to give me an idea of how it is.

  • was doing without the interaction with the database to put in Jsfiddle, and when testing worked normal, have idea of pq not working by JSON with the connection to the database?

  • Something in your PHP is wrong. Enable the errors and see what is.

Show 12 more comments

Browser other questions tagged

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