How do I pass a value from javascript to PHP?

0

I have a select that lists all my players:

<select name="jogador" id="cod_jogador">
    <option name=""></option>
    <?php foreach($jogadores as $jogador): ?>
        <option id="codigo" value="<?= $jogador['cod_jogador']?>">
            <?= $jogador['nome']?>
        </option>
    <?php endforeach; ?>
</select>

I want when the user chooses a player to change $ cod_player to be filled with the value of that select, so I made this script:

<script>

select = $('#cod_jogador');

select.bind("click", function(){
    $.ajax({
        url: 'idc-comparacao-jogador.php',
        type: 'post',
        dataType: 'html',
        data: {
            'codigo': $('#codigo').val()
        }
    }).done(function(data){

        console.log(data);

        $('#codigo').val('');

    });
});

</script>

The problem is that on the date it returns the HTML code of the page and not the value of my value, could anyone help me? How do I pass the value of my option to my PHP

    
asked by anonymous 10.08.2017 / 20:17

1 answer

0

First of all in <option...> can not have id="codigo" because where you have more than one option you will have more than one id with the same name "code" and this can not.

<select name="jogador" id="cod_jogador">
    <?php foreach($jogadores as $jogador): ?>
        <option value="<?= $jogador['cod_jogador']?>">
            <?= $jogador['nome']?>
        </option>
    <?php endforeach; ?>
</select>

<script>

$("body").on("change", "#cod_jogador", function(){
    select = $('#cod_jogador').val(); //Obtemos o valor do select com id="cod_jogador"
    $.ajax({
        url: 'idc-comparacao-jogador.php',
        type: 'post',
        dataType: 'html',
        data: {
            codigo: select,
        }
    }).done(function(data){

        console.log(data);

    });
});

</script>

For the date response to be the code only the idc-comparator-player.php content should look something like:

<?php
    echo $cod_jogador = $_POST['codigo'];
?>
    
10.08.2017 / 21:37