Francis Vargas Francis Vargas - 2 months ago 14
Javascript Question

Second drop down depends on my first drop down. How?

I have a two drop downs in my program, and I want it to be like this:


  • I have a list of employee and display/populate the list and put it
    inside of my first drop down.

  • Second is that, when I choose "Francis" the second drop down will
    have a value/event only for Francis and so on when I choose also another employee.



I think the first drop down is correct, but I want to get the value of it and put it inside in my SQL statement in the WHERE clause in my second drop down. How?




<tr>
<td><label for="cname">Client Name:</label></td>
<td><select name="cname" id="cname">
<option>Choose</option>
<?php
include("alqdb.php");
$result=mysqli_query($con, "SELECT ClientName FROM events");
while($row=mysqli_fetch_assoc($result)){
echo "<option>".$row["ClientName"]."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><label for="survey">Survey:</label></td>
<td><select name="survey" id="survey">
<option>Choose</option>
<?php
include("alqdb.php");
$result=mysqli_query($con, "SELECT EventTitle FROM events WHERE ClientName = 'Francis'");
while($row=mysqli_fetch_assoc($result)){
echo "<option>".$row["EventTitle"]."</option>";
}
?>
</select>
</td>
</tr>

Answer

Do a ajax request for the second select:

create a php file for the ajax request html:

<tr>
    <td><label for="cname">Client Name:</label></td>
        <td><select name="cname" id="cname">
            <option>Choose</option>
            <?php
                include("alqdb.php");
                $result=mysqli_query($con, "SELECT ClientName FROM events");
                    while($row=mysqli_fetch_assoc($result)){
                        echo "<option>".$row["ClientName"]."</option>";
                    }
            ?>
            </select>
        </td>
    </tr>
    <tr>
        <td><label for="survey">Survey:</label></td>
        <td><select name="survey" id="survey">
            <option>Choose</option>
        </select>
        </td>
    </tr>      

ajax.php

 <?php
     include("alqdb.php");
     $result=mysqli_query($con, "SELECT EventTitle FROM events WHERE ClientName = '"$_GET['cname']"'");
     while($row=mysqli_fetch_assoc($result)){
         echo "<option>".$row["EventTitle"]."</option>";
     }
 ?>

js:

<script>
$(function(){
 $('#cname').on('change',function(){
    $.ajax({
     url:ajax.php,
     data:{cname:$('#cname').val()};
     type:'get',
     contentType:'html',
     success:function(data){
     $('#survey').append(data);
    }
    });
});
});
</script>