0

I'm having some troubles to pass a JS variable to a PHP variable and then to a sql query.. take a look at the code:

The following val() method displays the selected value of the combobox and passes the js variable to a php variable properly:

<script>
  function val() {
    player = document.getElementById("combo").value;
    document.getElementById("demo").innerHTML = "<?php $player_name = '"+player+"'; echo "Player selected: "; echo $player_name;?>";
  }
</script>

Ok, so now $player_name is the option selected in the combobox.

<form method="POST">
  <select onchange="val()" id="combo"">
  <?php  
    foreach($names as $namearray => $value) { 
  ?>
  <option value="<?php echo $value;?>"><?php echo $value;     ?></option>
  <?php 
    } 
  ?> 
  </select>
  <input type="hidden" name="selected_text" id="selected_text" value="" />
</form>

Now, that's what's gonna happen after the user clicks the Send Button: ($player_name will be null, therefore, the sql query won't be executed properly)

  <?php
    if(isset($_POST['send'])) {
      $sql = "SELECT roleid FROM listrole WHERE name = '$player_name'";
      $result = $conn->query($sql);

      // output data of each row
      while($row = $result->fetch_assoc()) {
        $role_id = $row['roleid'];
        echo $role_id;
      }
  ?>

  <input style='height:30px;' type='submit' name='send' value='Send'>
</form>
Trevor
  • 13,085
  • 13
  • 76
  • 99
  • I'm afraid you can't pass javascript variables to PHP like that. The php code gets processed and rendered before the javascript ever runs. If you want to pass data to PHP from javascript, you'll either need to submit a form or make an ajax request. – Trevor Feb 08 '16 at 23:51
  • Agree to what [threed](http://stackoverflow.com/users/269061/threed) said. Javascript is client side language, and php is server side language. if you want to pass the variable to server side, then you have to make a form or ajax request – Budianto IP Feb 08 '16 at 23:54
  • I thought there was an easier way in order to do what, thanks anyways, I will try to get there! – Daniel Gomes Feb 09 '16 at 00:16

0 Answers0