Home > Software engineering >  @foreach data collection inside Ajax (Laravel)
@foreach data collection inside Ajax (Laravel)

Time:01-16

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 >
                <td>${person.user.name}</td>
                <td></td>
                <td >
                  <select  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 >
                <td>${person.user.name}</td>
                <td></td>
                <td >
                  <select  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!

CodePudding user response:

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:

@php
    $data_ku_item_options = '';
    foreach ($data_ku as $item) {
        $data_ku_item_options .= "<option value=\"" . $item->id . "\">" . $item->attendance->status . "</option>";
    }
@endphp

<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) => {
                    var options = "{{ $data_ku_item_options }}";
                    let list = `
                        <tr >
                        <td>${person.user.name}</td>
                        <td></td>
                        <td >
                            <select  aria-label=".form-select-sm example" name="absensi[${person.id}]">
                                ${options}
                            </select>
                        </td>
                        </tr>
                    `;
                    $('#data_anak').append(list);
                });
            }
        }
    });
});

</script>

And $data_ku = KelompokUmur::all(); change this line to:

$data_ku = KelompokUmur::with('attendance')->get();

CodePudding user response:

Use this to get the collection of array in the JS

var absen = {!! json_encode($kabsen->toArray()) !!}

Then iterate it using $.each method in jQuery

$.each(absen, function(index, value) {
                      list  = `<option value="${value.id}">${value.kode_absen}</option>`;
                    });
                    list  = 
  • Related