I've been hours and hours (and time is running out to get this working) trying to figure out how to fill a select with the cities from a previously selected state using AJAX
the PHP file looks like this:
include_once("../models/class-Zone.php");
$state= $_GET["st"];
$cities= Zone::getCities($state);
echo json_encode($cities);
When I ALERT the result using ajax:
$.post(
'../ajax/getcities.php?st='+stateid,
function(data) {
alert(data);
}
);
//I GET THIS:
[{"id":"08078","titulo":"BARANOA"},
{"id":"08001","titulo":"BARRANQUILLA"},
{"id":"08137","titulo":"CAMPO DE LA CRUZ"},
{"id":"08141","titulo":"CANDELARIA"},
{"id":"08296","titulo":"GALAPA"},
{"id":"08132","titulo":"JUAN DE ACOSTA"},
{"id":"08421","titulo":"LURUACO"}]
I haven't found a way to Iterate and fill a SELECT with this data. The select should look like this
<select name="city" id="city">
<option value="ID FROM THE JSON">TITULO FROM THE JSON ARRAY</option>
... AND FOR THE REST OF THE RESULTS
</select>
Thank you beforehand! I am seriously confused.
Decode the JSON first, then add HTML to the select for each city.
function(data) {
var cities = JSON.parse(data);
for(var c in cities) {
document.getElementById('city').innerHTML += '<option value="' + cities[c].id +'">' + cities[c].titulo + '</option>';
}
}