I want to choose chain select dropdown to get addres, while user select option country Indonesia then display select option state Jakarta, or user select country Malaysia then display select state Sabah.
below table MySQL
Countries table
+--ID--+----Negara----+
| 1 | Indonesia |
| 2 | Malaysia |
+------+--------------+
States table
+--ID--+---countrie_id---+---Provinsi----+
| 1 | 1 | Jakarta |
| 2 | 1 | Bali |
| 3 | 2 | Sabah |
| 4 | 2 | Serawak |
+------+-----------------+----------------+
the result that I want is below
select options countries
<select name="countries">
<option>Indonesia</options>
</select>
select options states
<select name="states">
<option>Jakarta</option>
<option>Bali</option>
</select>
controller Countries
public function index(){
$negara = $this->Countries->find('all')->extract('Negara');
$this->set(compact('negara'));
}
public function getCountries(){
$negara = $this->Countries->find('all')->extract('Negara');
return $this->response
->withType('application/json')
->withStringBody(json_encode([
'jQueryNegara' => $negara,
'result' => $result
]));
}
controller States
public function index(){
$provinsi = $this->States->find('all')->extract('Provinsi');
$this->set(compact('provinsi'));
}
public function getStates(){
$provinsi = $this->Countries->find("all")->extract('Provinsi');
return $this->response
->withType('application/json')
->withStringBody(json_encode([
'jQueryProvinsi' => $provinsi,
'result' => $result
]));
}
The form input cities add.ctp
<?= $this->Form->control('countrie_id', [
'type' => 'select',
'id' => 'jQueryNegara',
'options' => $negara
]); ?>
<?= $this->Form->control('province_id', [
'type' => 'select',
'id' => 'jQueryProvinsi',
'options' => $provinsi
]);
?>
the jQuery ajax inside cities add.ctp
$(function(){
$('#negara').on('change', function() {
var id = $(this).val();
var targeturl = '<?= Router::url(["controller"=>"countries","action"=>"getCountries"]); ?>';
if(id == '-1'){
$('#provinsi').html(`<option value="-1">Select State</option>`);
}else{
$("#divLoading").addClass('show');
$('#provinsi').html(`<option value="-1">Select State</option>`);
$.ajax({
type:'post',
url: targeturl,
data:'id='+id+'&type=state',
dataType: 'json',
success:function(result){
$("#divLoading").removeClass('show');
$('#provinsi').append(result);
}
});
}
});
});
I have try repeat and fix at bug, but still doesn’t work.
Thanx for someone that want to help me