Populate Another Select Dropdown from Database Based on Dropdown Selection

Populate another select dropdown from database based on dropdown selection

I would just make put the variables in javascript with php and then use javascript functions.. no jquery or AJAX needed.

However you need to have a foreign key for subcategories no matter what.. ie - For every record in subcat table you need to give it a catid so for referencing...

<?php
$db = new mysqli('localhost','user','password','dbname');//set your database handler
$query = "SELECT id,cat FROM cat";
$result = $db->query($query);

while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['id'], "val" => $row['cat']);
}

$query = "SELECT id, catid, subcat FROM subcat";
$result = $db->query($query);

while($row = $result->fetch_assoc()){
$subcats[$row['catid']][] = array("id" => $row['id'], "val" => $row['subcat']);
}

$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);

?>

<!docytpe html>
<html>

<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>

</head>

<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>

<select id='subcatsSelect'>
</select>
</body>
</html>

Populating Second Dropdown Based on first dropdown from the database table without using javascript

You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you

https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php

OR

https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/

Populate dropdown based on another dropdown via Database

You have add each option within the php loop too:

<?php 
$result=mysql_query("SELECT * from prog");
while($row=mysql_fetch_array($result))
{
?>
selbox.options[selbox.options.length] = new Option('<?php echo $row['prog_student_name']; ?>');<?php
}
?>

Do this for the other loops too. Furthermore, add this code to the beggining of your code. You just need it once.

<?php
include 'config.php';
mysql_select_db("dept_db",$con);
?>

How can i populate a dropdown list by selecting the value from another dropdown list

Do a html as given below for Make

<?php $sql = "SELECT * FROM country";
$result = $pdo->query($sql);
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php foreach ($result as $row) {
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
} ?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax

Write a ajax function get_states();

<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>

File getstates.php - Will get sub from the below file which will be appended to the div

if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql = "SELECT * FROM state WHERE country=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$country]);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
foreach ($stmt as $row) {
echo "<option value='" . $row['state_id'] . "'>" . $row['state_name'] . "</option>";
}
echo "</select>";
} else {
echo '';
}
}

Populate second dropdown based on the value selected in the first dropdown in flask using ajax and jQuery

I think you're almost there. I don't know python or flask, but I can give you the main idea.

  1. When you select the manager, you get the manager name and you have to send that name in the ajax call, so you can get it in your Route code and use it to filter the array. You can send that value using the data parameter of the ajax call...

    $(document).ready(function(){

    $("select#next").change(function() {

    var managerName = $(this).find('option:selected').text();

    $.ajax({
    type: 'GET',
    url: "/getEmployees",
    data: { manager: managerName }
    contentType: 'application/json',
    dataType: 'json'
    });
    });
    });
  2. In your ajax call, create a success callback function that will be called when you receive a successful response. Something like this...

    $(document).ready(function(){

    $("select#next").change(function() {

    var managerName = $(this).find('option:selected').text();

    $.ajax({
    type: 'GET',
    url: "/getEmployees",,
    data: { manager: managerName }
    contentType: 'application/json',
    dataType: 'json',
    success: function(response) {
    }
    });
    });
    });
  3. You could also add a check to verify if you've selected manager or unselected. In case you unselect manager, you have can empty the employee select, disable it, show all employees, or whatever you want.

    $(document).ready(function(){

    $("select#next").change(function() {

    if ($(this).val() != 'default') {

    var managerName = $(this).find('option:selected').text();

    $.ajax({
    type: 'GET',
    url: "/getEmployees",,
    data: { manager: managerName }
    contentType: 'application/json',
    dataType: 'json',
    success: function(response) {
    }
    });
    }
    else { // No manager selected.
    // Do what you wnat when there's no manager selected.
    // For example, if you'd want to empty and disable the employees select...
    $('select#sel_user').html('').prop('disabled',true);
    }
    });
    });

Now is where I have problems to help you, because of my lack of knowledge of python/flask:

  • In your Route code, you have to read the manager parameter sended with the GET ajax call. I don't know how you do that in python/flask but it has to be easy. In php would be just $_GET['manager']. With a quick search, it looks like it could be something like request.GET['username'], but you'll know it way better than me. You have to get that parameter and put that value in the last return line, something like...

    return session.query(Bookmarks).filter_by(Manager=request.GET['username'])
  • Is not clear to me the format of this response, so I don't know how to extract the info to create the employees select. Looking at your ajax call, you say the response is in JSON format, but I would need to see an example of that response to shw you the exact code. The idea is that you have to get that info and create the options in the success function of the ajax call, and then put that options in the employees select. Something like...

    // Imagine that your response is an array of objects similar to this
    // [{"name": "Tommy", "other": "value10"},{"name": "Jim", "other": "value32"},...]

    success: function(response) {

    var options = [];
    for (var i=0, l=response.length; i<l; i++)
    options.push('<options value="'+response[i].other+'">'+response[i].name+'<options>');

    $('select#sel_user').html(options.join(''));
    }

I think with all this you can have an idea of how to proceed, adapting it to your specific needs. I hope it helps.



Related Topics



Leave a reply



Submit