I have a php script that returns timezones from the form country SELECT and populates the timezone SELECT.
'US' produces ...
PHP
Timezones Array
(
[0] => America/Adak
[1] => America/Anchorage
[2] => America/Boise
[3] => America/Chicago
...etc...
[28] => Pacific/Honolulu
)
echo json_encode($timezones_array_above);
But I dont know how to handle the key/value data in javascript/jquery, so I had to create another loop in the php script to name the pair to use the javascript below.
PHP
// I WANT TO GET RID OF THIS EXTRA LOOP AND MOVE IT TO JAVASCRIPT PART BELOW!
foreach ($timezones as $key => $value) {
$json[] = array(
'id' => $value,
'name' => $value
);
}
echo json_encode($json);
HTML / JQUERY
$('#country').on('change', function (){
$.post('{$constant->get('AJAXPAGE')}/timezonesbycountry.php', {country: $(this).val()}, function(data){
/*
// I WANT TO HANDLE THE RAW TIMEZONE ARRAY HERE!
// AND REPLACE THIS WITH KEY & VALUE VARS...
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
*/
$('#timezone').html(options);
}, 'json');
});
How do I do this in javascript?
Here is the replacement I came up with, which works, but is this correct?
$('#country').on('change', function (){
$.post( "{$constant->get('AJAXPAGE')}/timezonesbycountry.php", {country: $(this).val()})
.done(function( data ) {
var result = JSON.parse(data);
var options = '';
$.each(result, function(k, v) {
options += '<option value="' + v + '">' + v + '</option>';
});
$('#timezone').html(options);
});
});