How do I pass a javascript value to PHP?

Asked

Viewed 59 times

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 that when the user choose a player the variable $cod_player is filled with the value of that select, for that 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

  • Use $('#player option:Selected'). val(); to get the value of the selected option

1 answer

0

First on <option...> can’t have the id="codigo" because where you have more than one option you will have more than one id with the same name "code" and this cannot.

<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 code only the content of idc-comparison-player.php should be something similar to:

<?php
    echo $cod_jogador = $_POST['codigo'];
?>
  • Unfortunately it didn’t work, it keeps returning the same html code, will it be because the url of my ajax is being directed to the same code that it is running?

  • If the URL is the same yes, it is due to this, ajax receives everything that is "Work" on the screen so to say, there at the end I left the code that should have the . php, tries to create a new . php and in it put those 3 last lines, then put this file to be called in the ajax URL.

Browser other questions tagged

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