How to receive the value of <select> in PHP when selecting an option

Asked

Viewed 97 times

1

How do I, so that when the user selects an option, the PHP variable $idCourse receive the value of the selected option.

I made this code just to show the idea:

Code

    <select name="valor" id="idCourse">
        <option value="1">Curso 1</option>
    </select>

    <?php 
       $idCourse = $_POST['valor'];
       $result = $pdo->selectAll($idCourse);
    ?> 
  • have to send using a form or using jquery

1 answer

1


I don’t know if you really need to do this with pure javascript. But with jQuery it’s much easier. See an example below:

Javascript / jQuery and HTML:

$('#idCourse').on('change', function() {

   alert(this.value);

  $.ajax({
     url: "caminho/nome_arquivo.php",
     method: "POST",
     data: { valor : this.value },
     dataType: "JSON"  
  }).done(function(response) {
     console.log(response);
  }).fail(function(err) {
     console.log(err);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="valor" id="idCourse">
    <option>Selecione</option>
    <option value="1">Curso 1</option>
</select>

PHP code:

<?php 
    $idCourse = $_POST['valor'];
    echo $idCourse;
    ...
?> 

Browser other questions tagged

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