在选择组合框值时,必须在从数据库中选择查询后动态显示标签

在选择组合框值时,必须在从数据库中选择查询后动态显示标签

问题描述:

In a file following code is written which populate the value of combobox :

<select id="company" required="required" class="form-control" value = "select"    name="subject_code" placeholder="Select" >
   <?php
     //Iterating list of subjects available to be filled .
    echo "<option> Select </option>";
     foreach ($subjects_to_fill as $subject_id => $subject_name) {
          # code...                             
             echo "<option value=".$subject_id."> ".$subject_name." </option>";

      }                                              
     ?>
</select> 

On selecting a particular item from the combobox, I want to display the faculty_name dynamically from faculty_table on the basis of $subject_id.

table structure:

faculty_table(faculty_id,faculty_name,subject_id)
subject_table(subject_id,subject_name,faculty_id)

You will need to use ajax for this task.

Add a <div> and below script in your current file.

<div id="faculty"></div>
<script type="text/javascript">
     function get_faculty()
       {
        var id = document.getElementById("company").value;
        var dataString = 'id='+ id;
        $.ajax
        ({
            type: "POST",
            url: "get_faculty.php",
            data: dataString,
            success: function(html)
            {
            $("#faculty").html(html);
            } 
        });
       }

</script>

Now create another get_faculty.php file in same folder which will be called on onchange event of company dropdown.

Write below code in that file

    if($_POST['id'])
     {
     $id=$_POST['id'];

     $con=mysqli_connect("localhost","username","pass","dbname");
     $sql=mysqli_query($con,"SELECT faculty_name from faculty_table where subject_id = ".$id);
                   while($row=mysqli_fetch_array($sql))
                   {
                       echo $row['faculty_name'];

                   }
     }

Dont forget to write mysqli_connect credentials and query accordingly.