简体   繁体   中英

Jquery drop down option on based previous selction

Is it possible to get data from the database based on the previous drop down selection?

For example:

<select id="paramscountries" class="chzn-done" style="display: none;" name="params[countries][]" multiple="true" size="10">
    <option value="1">Afghanistan</option>
    <option value="2">Albania</option>
    <option value="3">Algeria</option>
    <option value="4">USA</option>
</select>

If I select USA from the above list it will make a query & get all the states name from the database. For example from states.php & will show all the states name in another drop down selection without reloading that page.

You would need to use Javascript or jQuery for this and use it to post to a page that will return your results.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="paramscountries" class="chzn-done" style="display: block;" onchange="getNewList($(this).val());" name="params[countries][]" multiple="true" size="10">
    <option value="1">Afghanistan</option>
    <option value="2">Albania</option>
    <option value="3">Algeria</option>
    <option value="4">USA</option>
</select>

<select name="states" id="states">
</select>

<script type="text/javascript">
function getNewList(country) {
    $.post('post.api.php', {'api': 'getStates', 'countries': country}, function(response) {
        var obj = $.pareseJSON(response);
        $('#states').html(obj.states);
    });
}

post.api.php page

<?php

if(isset($_POST['api'])){

    if($_POST['api'] == 'getStates'){

        // sdet the countries array to a variable
        $countries = $_POST['countries'];

        // set a variable to hold the results
        $results = array();

        // query your db
        $stm = $db->prepare('SELECT * FROM `your_database` WHERE `country` IN("'.implode('","', $countries).'")');
        $stm->execute();
        if($stm->rowCount() > 0){
            foreach($stm->fetchAll(PDO::FETCH_ASSOC) as $row){
                $results['states'] .= '<option value="'.$row['stateName'].'">'.$row['stateName'].'</option>';
            }
        }            
        echo json_encode($results);
    }

}

I would do something like that. Hopefully there is enough here to get you rolling.

Try using jquery ajax request. something like this

jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#paramscountries').change(function(){
        $.ajax({
            url: 'states.php'
            ,data:{val: $(this).val()}
            ,dataType:'json'
            ,type: 'POST'
            ,success:function(data){
                for(var i = 0; i < data.length; i++){
                    var dropDownValue = '<option value="'+ data[i] +'">'+ data[i] +'</option>'
                    $('#secondDropDownList').append(dropDownValue);
                }
            }
        });
    });
});
</script>

In states.php

$con=mysqli_connect("localhost","user","password","db_Name");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($POST['val'])){
$var = $_POST['val'];
$result = mysqli_query($con,"SELECT * FROM table_name WHERE table_column_name = '$var'");
$arr = array();
while($row = mysqli_fetch_array($result)) {
   $arr[] =  $row['name'];
}
echo json_encode($arr);
}
mysqli_close($con);

In HTML

<select id="secondDropDownList"></select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM