Reputation: 4457
Hi I'd like some help please.
I'm having 2 dropdown menus. In the first one I pick the name of a city
<select id="select1" class="select" name="city">
<option value="101000000">city1</option>
<option value="102000000">city2</option>
<option value="103000000">city3</option>
</select>
and in 2nd one I want to display dynamicly all municipalities of the selected city each time
<select id="select2" name="municipality[]" multiple="multiple"></select>
So in order to fetch all municipalities I do this
<script>
$("#select1").on("change", function() {
var x = $("#select1").val();
$.ajax({
type: "POST",
url: "fetch_municipalities.php",
// async: false,
data:"level1="+x,
success:function(data){
// alert(data);
$("#select2").html(data).multiselect();
},
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
This is my fetch_municipalities.php
if(isset($_POST['level1'])) {
$post_lvl2 = $_POST['level1'];
// die($_POST['level1']);
// echo $_POST['level1'];
$sql = 'SELECT * FROM L_Areas WHERE CentralAreaID = ' . $post_lvl2;
$query = mysqli_query($db, $sql);
$filter_list_lvl2 = '';
while($row = $query->fetch_assoc()){
$name_lvl2 = $row['AreaName'] ;
$id_lvl2 = $row['AreaID'] ;
$central_lvl2= $row['CentralAreaID'] ;
// the option tags
$filter_list_lvl2 .= '<option value="' . $id_lvl2 . '">' . $name_lvl2 . '</option>';
}
echo $filter_list_lvl2;
}
So If I select city1 the first time I get all municipalities of city1, but when I select another city (eg city2) the municipalities don't change (remains from city1).
How can I fix this?
Upvotes: 0
Views: 97
Reputation: 26360
Try this :
$("#select2").multiselect();
$("#select1").on("change", function() {
$.ajax({
type: "POST",
url: "fetch_municipalities.php",
data: { level1 : $(this).val() },
success:function(data){
$("#select2").html(data).multiselect('refresh');
},
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Upvotes: 1
Reputation: 26360
I think I got it. Instead of :
data:"level1="+x
use:
data: { level1 : x }
Data must be an object, not a string.
(also, use var x = $(this).val()
to avoid fetching #select1
twice in the DOM.)
Upvotes: 0