Search code examples
phporacledropdown

How to create a dropdown based on selection in another dropdown in php?


This is the first time that I’m working with oracle. I’m kind of stuck at printing the values of the second dropdown on the page. I’m getting the right results in the browser’s response tab but I’m not sure why it is not getting printed on the main page. Upon selecting a value in the first dropdown, it should print the names in the second one.

Here's my code:

form.php

<div class="container">
    <div class="panel panel-default">
    <div class="panel-body">
        <div id="addroles" class="hide" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div id="resultRoleContent"></div>
        </div>  
             <form class="cmxform" action ='functions/processform.php' id="Form1" method="post">
           <legend> Faculty Transaction Form</legend>
            <label for="addname">Please Select School</label>
           <select class="form-control" name="school" id="school">
                <?php
                $nameslist = $getschool->getSchool();
                oci_execute($nameslist, OCI_DEFAULT);
                while ($row = oci_fetch_array($nameslist, OCI_ASSOC+OCI_RETURN_NULLS)) {
                    echo '<option value="' . $row['SCHOOLNAME'] . '">' . $row['SCHOOLNAME']. '</option>';
                }
                ?>
           </select>
            <label for="names">Please Select Name</label>
          <select class="form-control" name="names" id="names">
               <option value='0' >Select Name</option>

        </select>
            
        </form>

    </div>
</div>       
<script>
$(document).ready(function(){
  $('#school').change(function(){
 var schoolname = $(this).val();
 $('#names').find('option').not(':first').remove();
 // AJAX request
 $.ajax({
   url: 'getUsers.php',
   type: 'post',
   data: {request: 1, primaryschool: schoolname},
   dataType: 'json',
   success: function(response){
     var len = response.length;

     for( var i = 0; i<len; i++){
       var firstname = response[i]['FIRSTNAME'];
       $("#names").append("<option value='"+firstname+"'>"+firstname+"</option>");
     }

   }
    });

  });
  });
</script>

getUsers.php

<?php
$dbUser = "xxxx";
$dbPass = "xxxx";
$dbConn = "(DESCRIPTION = (ADDRESS = (PROTOCOL=TCP)(HOST=xxxx)(PORT=1521))(CONNECT_DATA=(SID=xxxx)))";
$conn = oci_connect($dbUser, $dbPass, $dbConn);
$request = 0;
if(isset($_POST['request'])){
  $request = $_POST['request'];
 }
if($request == 1){
   $schoolpropername = $_POST['primaryschool'];
   $sql =oci_parse($conn,"SELECT * FROM person Where primaryschool = :primaryschool Order by firstname");
   oci_bind_by_name($sql, ':primaryschool', $schoolname);
   oci_execute($sql);
    ?>
   <select class="form-control" name="names" id="names">
    <?php
    while($result = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS)){
    echo '<option value="' . $result['FIRSTNAME'] . '">' . $result['FIRSTNAME']. '</option>';

  }    
   
}

?>
</select>

I'm getting the right results in the browsers response tab. It is only not getting printed on the web page. There's no error in the error_log. I referred to a few similar questions as well but didn't get the answer hence posted it.


Solution

  • Try to change this:

    SCRIPT

        <script>
        $(document).ready(function(){
          $('#school').change(function(){
             var schoolname = $(this).val();
             $('#names').find('option').not(':first').remove();
             // AJAX request
             $.ajax({
               url: 'getUsers.php',
               type: 'post',
               data: {request: 1, primaryschool: schoolname},
               success: function(response){
                  $("select#names").html('<option value="0">Select Name</option>');
                  $("select#names").append(response);
               }
           });    
        });
     });
    </script>
    

    getUsers.php

    <?php
    $dbUser = "xxxx";
    $dbPass = "xxxx";
    $dbConn = "(DESCRIPTION = (ADDRESS = (PROTOCOL=TCP)(HOST=xxxx)(PORT=1521))(CONNECT_DATA=(SID=utf8devl)))";
    $conn = oci_connect($dbUser, $dbPass, $dbConn);
    $request = 0;
    if(isset($_POST['request'])){
      $request = $_POST['request'];
     }
    if($request == 1){
       $schoolpropername = $_POST['primaryschool'];
       $sql =oci_parse($conn,"SELECT * FROM person Where primaryschool = :primaryschool Order by firstname");
       oci_bind_by_name($sql, ':primaryschool', $schoolname);
       oci_execute($sql);
       $response = '';
    
       while($result = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS)){
        $response .= '<option value="' . $result['FIRSTNAME'] . '">' . $result['FIRSTNAME']. '</option>' . PHP_EOL;
    
      }    
       echo $response;
    }
    

    Also this can be done using JSON response:

    getUsers.php

    ...
    $response = [];
        
    while($result = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS)){
       $response[] = $result['FIRSTNAME'];  
    }    
    echo json_encode($response);
    ...
    

    Jquery

    ...    
    $.ajax({
       url: 'getUsers.php',
       type: 'post',
       data: {request: 1, primaryschool: schoolname},
       dataType: 'json',
       success: function(response){
          $("select#names").html('<option value="0">Select Name</option>');
          var arr = jQuery.parseJSON(response);
          $.each( arr, function( key, value ) {
             $("select#names").append('<option value="'+ value +'">'+ value +'</option>');
          });          
       }
    });
    ...
    

    UPDATE

    Here is the confirmation produced on my localhost:

    HTML

    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function(){
                    $('#school').change(function(){
                        var schoolname = $(this).val();
                        $('#names').find('option').not(':first').remove();
                        // AJAX request
                        $.ajax({
                          url: 'resourse.php',
                          type: 'post',
                          data: {request: 1, primaryschool: schoolname},
                          success: function(response){
                             $("select#depend").html('<option value="0">Select Name</option>');
                             $("select#depend").append(response);
                          }
                      });    
                   });
                });        
            </script>
        </head>
        <body>
            <select id="school">
                <option value="1">One</option>
                <option value="2">Two</option>
            </select>
            <select id="depend">
                
            </select>
        </body>
    </html>
    

    resourse.php

    <?php
    $array = [
        "Alex",
        "Peter",
        "Sara"
    ];
    $out = '';
    
    foreach ($array as $val){
        $out .= '<option value="' . $val . '">' . $val. '</option>' . PHP_EOL;
    }
    
    echo $out;
    

    The above example work as expected.