-2

My project right now has two dropdown menu. One is with color and the other is with the members of that color. The goal is to use JS so if I select "Red", only members in red show up on the second dropdown. I have my SQL table below and my script. I am not sure where to start so some help would be nice.

SQL:

+--------+--------------+
| Color  | MemberName   |
+--------+--------------+
| Red    | Joe Bob      |
| Red    | Catherine    |
| Blue   | Tommy        |
| Orange | John Razks   |
| Black  | Trevor Smith |
+--------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+

PHP Code:

<!DOCTYPE html>
<html>
<head>
 <title>Test Page</title>
 <script src="jquery.js"></script>
</head>

<body>
<?php
function load_Color(){
 $conn=mysqli_connect("#variable");
 if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
 else{
 $output='';
 $sql = "SELECT * from Color order by Color ASC";
 $result = mysqli_query($conn, $sql);
 while($row=mysqli_fetch_array($result)){
  $output .= '<option value="'.$row["Color"].'">'.$row["Color"].'</option>';
 }
 return $output;
 }
}
?>
<div class="formatbody" id="formatbody">
   <div class="category_div" id="category_div">Color:
    <select id="color" name="color">
     <option value="">Select Color</option>
      <?php echo load_Color(); ?>
    </select> 
   </div> 
   <div class="sub_category_div" id="sub_category_div">Individual: 
    <select name="individual" id="individual">
     <option value="">Select Individual</option>
    </select>
   </div>
</div>
</body>
</html>

<script>
$(document).ready(function(){
 $('#color').change(function(){
  var Color = $(this).val();
  $.ajax({
   url: "fetch.php",
   method: "POST",
   data:{color: Color},
   dataType: "text",
   success: function(data)
   {
    $('#individual').html(data);
   }
  });
 });
});
</script>

Fetch.PHP:

<html>
<body>
<?php
 $conn=mysqli_connect("#Variable");
 if(!$conn){ die("Connection Failed".mysqli_connect_error()); }
 else{
 $output='';
 $sql = "SELECT MemberName from Members where Color = '".$_POST["color"]."' ORDER BY MemberName ASC";
 $result = mysqli_query($conn, $sql);
 $output = '<option value="">Select the Individual</option>';
 while ($row=mysqli_fetch_array($result))
 {
  $output .='<option value="'.$row["MemberName"].'">'.$row["MemberName"].'</option>';
 }
 }
 
 
 echo $output;
 ?>
</body>
</html>
  • 1
    you need to send an ajax request that holds the chosen color, then filter the individuals data by the chosen color, and respond the filtered data to your page so you can finally build the dynamic list – Mohammad Apr 03 '17 at 14:28
  • Could you give an example? @Mohammad – catung555555 Apr 03 '17 at 14:31
  • You tagged the question with `jQuery`, so have a look at [**jQuery Ajax**](http://api.jquery.com/jquery.ajax/) to query your backend and [**jQuery on**](http://api.jquery.com/on/) for using binding to control events of your dropdown such as the `change` event, etc.. Also check out other SO posts for what you need, such as [**Get selected value of a dropdown's item using jQuery**](http://stackoverflow.com/questions/2780566/get-selected-value-of-a-dropdowns-item-using-jquery) That should get you started. – Nope Apr 03 '17 at 14:32
  • @catung555555 Please use SO to find one of hundreds of SO posts about ajax , selecting values from dropdowns, binding to events, etc.. Such as ► [**using jquery $.ajax to call a PHP function**](http://stackoverflow.com/questions/2269307/using-jquery-ajax-to-call-a-php-function) - When you have some code you have issues with please post that code and we can help you find out what the problem is. – Nope Apr 03 '17 at 14:33
  • @catung555555 check my answer – Mohammad Apr 03 '17 at 14:46
  • @Fran I've attempted a code above. The color dropdown works, but I can't figure out the second. Could you assist? – catung555555 Apr 03 '17 at 15:47

2 Answers2

0

you need to follow these steps, for example:

html:

<select name="color">
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="green">green</option>
</select>

<select name="individuals"></select>

js:

<script>
    $('select[name="color"]').change(function(){
        var selectedColor = $(this).val();

        $.ajax({
            url: 'url-to-filter-individuals.php',
            method: 'post',
            data: {color:selectedColor},
            dataType: 'json',
            success: function(response){
                if(response['status']==='success'){

                    var html = '';

                    for(var i=0; i<response['data'].length; i++){
                        html += '<option value="'+response['data'][i]['id']+'">'+response['data'][i]['name']+'</option>';
                    }

                    $('select[name="individuals"]').after(html);
                }
            }
        });
    });
</script>

url-to-filter-individuals.php :

<?php
if(!empty($_POST['color'])){

    $color = $_POST['color'];

    // suppose I have connection to db in $con variable

    $stmt = $con->prepare("SELECT * FROM individuals_table iTable WHERE iTable.color LIKE ?");

    if($stmt){

        $stmt->bind_param('s',$color);

        if($stmt->execute()){

            /* Get the result */
           $result = $stmt->get_result();

           /* Get the number of rows */
           $num_of_rows = $result->num_rows;

           if($num_of_rows > 0){

                $data = array();

                while ($row = $result->fetch_assoc()) {
                    $data[] = array('id'=>$row['id'],'name'=>$row['name']);
               }

               /* free results */
               $stmt->free_result();

               /* close statement */
               $stmt->close();

               echo json_encode(array('status'=>'success','data'=>$data));
               exit(0);
           }
        }
    }
}
echo json_encode(array('status'=>'failure'));
exit(0);
Mohammad
  • 3,449
  • 6
  • 48
  • 75
0

You can just store the data in javascript object. Then you can access it and create your list dynamically

HTML:

    <body>
    <form id="blah">
        Color:
        <select id="committee" name="committee" onchange="committeeSelected(this.value);">
            <option value="">Select Color</option>
            <option value="Red">RED</option>
            <option value="Blue">BLUE</option>
            <option value="Black">BLACK</option>
            <option value="Orange">ORANGE</option>
        </select>

        <div class="sub_category_div" id="sub_category_div">
        Individual: 
        <select name="senator" id="senator">
        </select>
        </div>
  </form>
</body>

javascript:

<script type="text/javascript">
    var data = 
    {
        "Red":[
            "Joe Bob",
            "Catherine"
        ], 
        "Blue":[
            "Tommy"
        ],
        "Black":[
            "Trevor Smith"
        ],
        "Orange":[
            "John Razks"
        ]
    };

    var colors = [ "Red", "Blue", "Black", "Orange"];

    function committeeSelected(selected){       
        // get placeholder
        var senator = document.getElementById("senator");

        // first clear everything
        while(senator.firstChild)
        {
            senator.removeChild(senator.firstChild);
        }

        // first node is always select individual
        createOption("Select Individual");

        // here we need to generate listbox
        for(i=0; i<data[selected].length;i++)
        {
            var a = data[selected][i];

            createOption(a);
        }
    }

    function createOption(value){
            // attribute storing color value
            c = document.createAttribute("value");
            c.value=value;

            // textnode for storing color value
            cText = document.createTextNode(value);

            // append attribute node
            option = document.createElement("option");
            option.setAttributeNode(c);

            option.appendChild(cText);

            // append child
            senator.appendChild(option);
    }
</script>
Matija K.
  • 185
  • 1
  • 8