I'm trying to create a Dynamic Dependent Dropdown via Ajax and CodeIgniter 4. However, I could not make it work. Can you help me figure out what's wrong? I'm trying to follow this tutorial online: LINK
Error on the console
jquery.min.js:2
POST http://localhost/sidsci/public/sd/getAjaxBrgy 500 (Internal Server Error)
Database
mcb_id | mcb_name | mcb_brgy
View
<div class="form-row">
<div class="form-group col-md-6">
<label><b>Municipal / City<span class="text-danger">*</span></b></label>
<select name="s_muncity" class="form-control" id="s_muncity" required>
<option value="">-Select-</option>
<?php foreach($mcb as $mcb_row):?>
<option value="<?= $mcb_row->mcb_name;?>"><?= $mcb_row->mcb_name;?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group col-md-6">
<label><b>Barangay<span class="text-danger">*</span></b></label>
<select class="form-control" name="s_brgy" id="s_brgy" required></select>
</div>
</div>
$('#s_muncity').change(function(){
var mcb_name = $(this).val();
$.ajax({
url:'<?=base_url('/sd/getAjaxBrgy')?>',
method: 'POST',
data: {mcb_name: mcb_name},
dataType: 'json',
success: function(response){
$('#s_brgy').find('option').not(':first').remove();
$.each(response,function(index,data){
$('#s_brgy').append('<option value="'+data['mcb_brgy']+'">'+data['mcb_brgy']+'</option>');
});
}
});
});
Controller
public function getAjaxBrgy(){
$model = new McbModel();
$postData = array(
'mcb_name' => $this->request->getPost('mcb_name'),
);
$data = $model->getBrgyData($postData);
echo json_encode($data);
}
Model
public function getBrgyData($postData) {
$sql = 'select mcb_brgy from mcb where mcb_name ='.$postData['mcb_name'];
$query = $this->db->query($sql);
return $query->getResult();
}
I also have <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
in my header part.
mcb_barangay
but you're usingselect mcb_brgy ...
in your query, which is slightly different. Are you sure the column name you're using in your query is correct?mcb_brgy
.