I’m completely new to ajax and trying to find a workaround how to complete these scenario since I can’t find any that works for me.
I’m finding a way to populate the dropdown selection using foreach using AJAX. How I’m able to achieve it? I’m completely stuck here. Here’s the AJAX script.
$('#kelompokumur_id').change(function() {
var id = $(this).val();
$.ajax({
url: "{{url('fetch-anak')}}/"+id,
type: 'get',
dataType: 'json',
success: function(response) {
if(response.success){
let dataArray = response.data
$('#data_anak').empty()
let res = dataArray.map((person, index) => {
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">
<option value="">Pilih Absensi</option>
<option value="1">PRESENT</option>
<option value="2">PERMIT</option>
<option value="3">SICK</option>
<option value="4">ALPHA</option>
</select>
</td>
</tr>
`;
$('#data_anak').append(list);
});
}
}
});
});
And here’s the script that I tried to get the collection,
return view('anak.absensi._inputabsen', compact('data_ku'));```
I tried this method, but it returns null since it’s the closest I can get. Others show errors.
let list = `
<tr class="btn-reveal-trigger">
<td>${person.user.name}</td>
<td></td>
<td class="text-end">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" name="absensi[${person.id}]">`
@foreach($data_ku -> item)
<option value="{{$item -> id}}">{{$item -> attendance -> status}</option>
@endforeach
`</select>
</td>
</tr>
`;
On controller:
public function create()
{
$data_ku = KelompokUmur::all();
$kabsen = kodeabsensi::all();
// dd($kabsen->toArray());
return view('anak.absensi._inputabsen', compact('data_ku', 'kabsen'));
}
when I dd($data_ku), this returns:
0 => array:6 [▼
"id" => 1
"kode_absen" => "AM"
"nama_absen" => "Anak Malas"
"keterangan" => "Anak Malas"
"created_at" => "2023-01-13T17:27:49.000000Z"
"updated_at" => "2023-01-13T17:27:49.000000Z"
]
Any help would be appreciated, thanks!
2
Answers
Use this to get the collection of array in the JS
Then iterate it using $.each method in jQuery
While in the
*.blade.php
file you can do something like this. I did it outside of the script tags but you can also perform it inside:And
$data_ku = KelompokUmur::all();
change this line to: