1

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) {

    });
}
daedsidog
  • 1,732
  • 2
  • 17
  • 36
Alvin
  • 73
  • 1
  • 8

4 Answers4

0

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);
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
kshitij
  • 642
  • 9
  • 17
0

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 );  
M.Tamil
  • 74
  • 4
0

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

Gezero
  • 21
  • 3
0

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.

Alvin
  • 73
  • 1
  • 8