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

1

How do I, when the user selects an option, the $idCourse PHP variable receives 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);
    ?> 
    
asked by anonymous 09.04.2018 / 01:22

1 answer

1

I do not know if you really need to do this with pure javascript. But with jQuery and everything much easier. Here's 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><selectname="valor" id="idCourse">
    <option>Selecione</option>
    <option value="1">Curso 1</option>
</select>

PHP Code:

<?php 
    $idCourse = $_POST['valor'];
    echo $idCourse;
    ...
?> 
    
09.04.2018 / 02:11