How to access jQuery variable in PHP and PHP variable in jQuery?

Viewed 37

What I want to do:

  • I want to get a value from a select element
  • And then I want the specific record from the database on the basis of that value.
  • Finally, gets the record and displays it in an input field

This is my code:

enter image description here

1 Answers

You can't pass jQuery variable to PHP as such, however you can do same thing through ajax, where just pass selected value through ajax to PHP file and get returned result display in input field

<script>
  $("#chooseRoles").change(function(e){
e.preventDefault();
 $.ajax({
     url: 'getValue.php', 
    data: 'selectedRole='+$(this).val(),
    type: 'POST',
    success: function(result){
       $("#userRoles").val(result);
    }
  });
});

PHP CODE (getValue.php);

$roles = Roles::find($_POST['selectedRole']);
echo $capabilities = $roles->capabilities;
Related