I need to create dynamic dropdown option. Second select depends of first input. I want to make ajax request from cakephp app to action in controller but I am stuck with ajax code.
I tried:
<?= $this->Form->select('country_id' ,$optionsCountry, ['id' => 'country_id'], 'onclick' => 'getcit'); ?>
<?= $this->Form->select('Cities', $optionsCities); ?>
Than I want to create function which will be called on change of select option but I am stuck.
<script>
function getcities(str){
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function (){
xhttp.open('POST', 'controller' => 'cities', 'action' => 'getcit',+str , true);
xhttp.send();
}
}
I'm not sure how to call function in html, onchange? onselect? And how to fetch data from first input, send it to controllers action, fetch data from controller and set it in another select?
Thank you, Best regards,
I found jquery.ajax as maybe simpler solution but I got stuck again:
<script>
$(document).ready(function){
$('#country_id').change(function () {
$.ajax({
url: "",
data: "",
type: 'POST'
});
});
}
;
Can you help me with:
Thank you
You must create ajax call after first <select>
change, which returns data for second <select>
.
function getcities(id) {
$.ajax({
method: 'POST',
url: 'some.php',
data: {
country_id: id
},
success: function (data, status) {
$('.second_select').html(data); // If returns as html
}
});
return;
}