Reputation: 53
I've been trying to make two dependent dropdowns. And I'm using PHP commands to get all the data values from an API. Now I have been able to populate the first dropdown but then for the second dropdown I am making an Ajax POST call since I need to use a PHP function Here's the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('select#district_area').change(function(){
var district_val = $(this).val();
console.log(district_val);
$.ajax({
url:"c.php",
method: "POST",
data: {'district_val':district_val},
success:function(data){
console.log(data);
$('select#district_area').html(data);
}
});
});
});
</script>
<body>
<div>
<select name="district_area" id="district_area">
<option> Select District </option>
<?php foreach($districts as $first){ ?>
<option><?php print($first['district_name']); ?></option>
<?php } ?>
</select>
<p></p>
<select name="delivery_area" id="delivery_area">
<option>Select Delivery Area</option>
</select>
</div>
</body>
Here $districts is the array of values.
c.php
:
$district_value = $_POST['district_val'];
$del_val = search_recursive_key_value($decoded, 'name', $district_value);
?>
<select name="delivery_area" id="delivery_area">
<option><?php echo $del_val; ?></option>
</select>
The Ajax POST call works. The response I get is not in JSON format. I've been trying to get it in JSON format using dataType:"JSON"
but it still doesn't return it in JSON and so I'm not being able to make the second dependent dropdown.
I've console logged it
How do I populate a dropdown using these values?
Upvotes: 0
Views: 1427
Reputation: 278
You need to have the HTML tags for generating options and append them to select dropdown.
Try something like this in your success function in AjaxCall:
$("select#delivery_area").append('<option value=' + "data.district_val" + '>' + data.district_val + '</option>');
If your data length is more than one, then you need a for loop to generate each options and append each one to select dropdown.
Upvotes: 2
Reputation: 53
The solution that worked:
$(document).ready(function(){
$('select#district_area').change(function(){
var district_val = $(this).val();
console.log('District selected:',district_val);
$("select#delivery_area").empty();
$.ajax({
url:"c.php",
method: "POST",
data: {'district_val' : district_val},
success:function(data){
console.log(data);
splitData = data.split(",");
console.log(splitData);
for(var i=0; i<splitData.length-1; i++){
$("select#delivery_area").append('<option value="">' + splitData[i] + '</option>')
}
}
});
});
});
Upvotes: 0
Reputation: 206
not too sure what you are trying to do.. maybe this will help:
$('select#district_area').html(data);
should be
$('select#delivery_area').html(data);
Upvotes: 0