-2

I have two drops downs on my page.

  1. I have a drop directly taken from DB.
  2. I have a drop totally depends on the selection from dropdown 1 and taken from db.

I have both of these drop-downs inside a modal. I am not sure how to insert the javascript variable to dropdown 2.

Here is my code:

Dropdown 1:

<select class="selectpicker form-control mt-2" id="schoolname" name="schoolname" data-width="" title="School" onChange=reload(this.form)>   
<?php 
 $prod_query = "SELECT * FROM my_school_class";
 $prodresult = mysqli_query($DBconnect, $prod_query);
 while($r = mysqli_fetch_array($prodresult)) 
 {
   if (!empty($schoolName) && $schoolName == $r['schoolName']) 
   {
     $selected = 'selected="selected"';
   } 
   else 
   {
      $selected = '';
   } 

   echo "<option ".$selected." value=".$r['schoolName'].">".$r['schoolName']."</option>"; 
 } ?>
</select>

Dropdown 2:

<select class="selectpicker form-control mt-2" id="classname" name="classname" data-width="" title="class">   
    <?php 
     $prod_query = "SELECT * FROM my_class WHERE school="JAVASCRIPT VARIABLE SHOULD COME HERE";
     $prodresult = mysqli_query($DBconnect, $prod_query);
     while($r = mysqli_fetch_array($prodresult)) 
     {
       echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>"; 
     } ?>
    </select>

Javascript writing correctly to console:

<script language=JavaScript>
function reload(form)
{
    var val=form.schoolname.options[form.schoolname.options.selectedIndex].value;
    console.log (val);
}
The above variable prints the selection correctly on the console in chrome.

And I have all these inside a modal. Let me know how to fix this?

Thanks!

Sanjana Nair
  • 2,663
  • 6
  • 26
  • 44
  • Does this help? [pass value from a first select to a second select](https://stackoverflow.com/a/64089967/2430549) – HoldOffHunger Sep 30 '20 at 00:30
  • @HoldOffHunger - Thanks for the quick reply. I looked at the link you sent both the dropdowns are hardcoded. How do I use that for values from DB? – Sanjana Nair Sep 30 '20 at 00:34
  • That was actually the same question as on that link, by that OP (look at comments below my answer there). I give an explanation there, *In your code example, you have only one select list. You'll want to make one select list for each list you want, and make them start out hidden. Then use my code above. Change $('#sel2').empty();*. You're right, I should update my answer there. But it's difficult to make a simple, js code sample that does api queries. Anyway, let me know if it helps? I can improve it with more dynamic examples, etc.. – HoldOffHunger Sep 30 '20 at 00:52
  • I checked it. In your answer, you have said $('#sel2').append(''); $('#sel2').append(''); This is hardcoded. In my case, I have to pull the data from DB according to selection from 1. – Sanjana Nair Sep 30 '20 at 00:58
  • I state explicitly, ***You'll want to make one select list for each list you want***. That means, you make one list, hide it, and show it, as needed. This is **NOT** hardcoded, because it's based on the DB values. On the other hand, just like that question, users were questioning the value of helping a user who is unwilling to attempt solutions posted and given to them. So, good luck. – HoldOffHunger Sep 30 '20 at 01:15
  • use ajax instead to display it – Jerson Sep 30 '20 at 01:25
  • @Jerson can you give some idea on how to proceed? – Sanjana Nair Sep 30 '20 at 01:34

2 Answers2

-1

Call ajax like this (pure vanilla js)

    function reload(form)
    {
        const id = form.schoolname.options[form.schoolname.options.selectedIndex].value

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/fetch_second.php/');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.onload = function() {
            if (xhr.status === 200) {
                const data = xhr.responseText
                let elem = document.querySelector( 'css-selector (#container id)')
                elem.appendChild(responseText)
                
            }
            else if (xhr.status !== 200) {
                console.log('Request failed.  Returned status of ' + xhr.status);
            }
        }
        xhr.send(encodeURI('id=' + id))

    }

and change

this css-selector (#container id) to your container id or className from your modal

And in your fetch_second.php

        $schoolName = $_POST['id']; 

        $prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
        $prodresult = mysqli_query($DBconnect, $prod_query);
        while($r = mysqli_fetch_array($prodresult)) {
            
            echo "<option value=".$r['className'].">".$r['className']."</option>";

        } 
Jerson
  • 1,700
  • 2
  • 10
  • 14
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 30 '20 at 10:10
-1

use this using JQUERY index.html

  $(document).on('change','#schoolname',function(){
     var schoolname = $('#schoolname').val();
     $('#classname').empty();
     $('#classname').append('<option value="" disabled selected>Choose your option</option>');
     $.ajax({
                 url: 'GetClassname.php',
                 type: 'POST',
                 data: {schoolname : schoolname },
                 success: function(data) {
                    $('#classname').append(data);
                 }
             });
  });

GetClassname.php

<?php
include('../config.php');
$schoolname = $_POST['schoolname'];
    
$prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult)) {
    echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>"; 
} 
?>
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 30 '20 at 10:09