'Populate dropdown2 from onChange event of dropdown1

I need to write a code where i need to populate a dropdown1 from mysql table based on the selection of another dropdown which also where in need to give values of dropdown as numeric value as item id from mysql table , but script.js not accepting any numeric value .Am quite new to this concept please help me to resolve this issue, thank you

HTML PART


<div>
    <select class="custom-select" style="width: 150px;" id="dropdown1" onchange="onChange()">
        <option selected disabled>Select Role </option>
        <?php
enter code here
            $sql = "SELECT * FROM category";
            $result = $conn->query($sql);
   //Populate dropdown2 from onChange event of dropdown1 
            if ($result->num_rows > 0){
                    // output data of each row
                    while($row = $result->fetch_assoc()){
                    echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
                }
            } else{
                echo "Sorry No Role Availabe for Now";
            }
            $conn->close(); 
        ?>
    </select><br/>
    <span id="choosen"></span>
</div>

JS PART


<script>
    function onChange(){
        var idforquery =document.getElementById('dropdown').value;
        document.getElementById("choosen").innerHTML="
        // Here we generate another dropdown of behalf of selected dropdown option 
        <div>
            <select class="custom-select" style="width: 150px;" id="dropdown1">
                <option selected disabled>Select Role </option>
                <?php
                    $sql2 = "SELECT * FROM sub_category WHERE cat_id =idforquery;";
                    $result = $conn->query($sql2);
        
                    if ($result->num_rows > 0){
                            // output data of each row
                            while($row = $result->fetch_assoc()){
                            echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
                        }
                    } else{
                        echo "Sorry No Role Availabe for Now";
                    }
                    $conn->close(); 
                ?>
            </select><br/>
        
            <span id="choosen1"></span>
        </div>";
    }
</script>


Solution 1:[1]

This is not going to work. PHP code is only executed when the client loads the page. If you want the <option> tags to change dynamicaly after the page has loaded, you need to use an asynchronous request (AJAX).

Here is a guide on how to use AJAX requests using PHP and jQuery.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maqc