I am trying to dynamically load cities into the select tag in HTML. I am able to choose the state and then i want to load the city through an ajax call.
As far as console-logging the returned data it works, I am stuck with how i load this into the select option tags. Please help.
<select name="state" class="state">
<option value="" selected disabled>Choose State</option>
<?php foreach ($states as $state) {
echo "<option value='".$state->id."'>$state->name";
}?>
</select>
<select name="city" class="city" id="city">
<option value="" selected disabled>Choose City</option>
</select>
$.ajax({
type: "POST",
url: "includes/get_city.php",
data: {
state: selectedState
},
}).done(function(data) {
console.log(data); // Works when I console log
//Don 't know if this is the way
$('#city' > option).each(data, function(index, value) {
});
}
Try this (assuming index and value are used in correct manner):
var text = '';
$.each(data, function(index, value){
text += '<option value="'+index+'">'+value+'</option>';
});
$('#city').html(text);
// or you can use append to put value in select
$('#city').append(text);
If your ajax response is similar to the states collection in your code then you could use
var toAppend = '';
$.each(data, function(index, city){
toAppend += '<option value="'+city.id+'">'+city.name+'</option>';
});
$('#city').append(toAppend );
If you are getting json response try this:
$.ajax({
type: "POST",
url: "includes/get_city.php",
data: {
state: selectedState
},
dataType: "json"
}).done(function(data) {
$.each(JSON.parse(data), function () {
$('#city').append('<option value="'+data.id+'">'+data.name+'</option>');
});
});
this code
$('#city' > option).each(data, function(index, value)
will not work because not appends "options" but searching for existing ones
You can also debug it from chrome (press F12) to checkout if you have a syntax error or something
Watched a video online and figured this was one way of doing it.
$('#state').change(function() {
var state_id = $('#state').val();
$.ajax({
url: 'includes/get_city.php',
method: 'post',
data: 'state_id=' + state_id
}).done(function(cities) {
console.log(cities);
cities = JSON.parse(cities);
$('#city').empty();
cities.forEach(function(city) {
$('#city').append('<option>' + city.name + '</option>');
})
});
});
Appreciate all the answers.