Filtering select options by related values using jQuery post in Laravel, how can I display data returned from the controller?

huangapple go评论65阅读模式
英文:

Filtering select options by related values using jQuery post in Laravel, how can I display data returned from the controller?

问题

I'm trying to filter my select option with another select option using jQuery post. When a certain outlet is selected, the next select option, which is "karyawan," should only display karyawan assigned to that outlet. However, I don't know how to handle the response I get from the controller. Can anyone help me?

This is my view:

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Outlet</label>
    <div class="col-md-9 col-sm-9 col-xs-12">
        <select class="form-control" name="outlet" id="outletSelect">
            <option value="">Choose an option</option>
            @foreach($outlets as $it)
            <option value="{{$it->id}}">{{$it->nama}}</option>
            @endforeach
        </select>
    </div>
</div>
<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Karyawan</label>
    <div class="col-md-9 col-sm-9 col-xs-12">
        <select class="form-control" name="nama">
            @if (isset($kritems))
            @foreach($kritems as $its)
            <option value="{{$its->nama}}">{{$its->nama}}</option>
            @endforeach
            @endif
        </select>
    </div>
</div>

This is my script:

$(document).ready(function() {
    $('#outletSelect').change(function() {
        var selectedOutlet = $(this).val();
        var token = "{{ csrf_token() }}";
        $.ajax({
            url: "{{ route('nilai.choose') }}",
            method: 'POST',
            data: {
                outlet: selectedOutlet,
                '_token': token
            },
            success: function(response) {
                console.log(response);
                // Handle the response here and update the Karyawan select options
            },
            error: function() {
                alert('Failed to fetch karyawan.');
            }
        });
    });
});

This is my controller:

public function choose(Request $request)
{
    $outlet = Outlet::findorfail($request->outlet);
    $outlets = Outlet::all();
    $kritems = Karyawan::where('outlet', $request->outlet)->get();

    return $kritems;
}

And this is the response I get:

[{
    "id": 2,
    "created_at": "2023-05-31T08:36:33.000000Z",
    "updated_at": "2023-05-31T08:48:18.000000Z",
    "user_id": 18,
    "nama": "Hidayat",
    "nik": "3376012705950002",
    "nomor": "333444",
    "alamat": "jlnjlm",
    "email": "dayat@test.com",
    "pendidikan": "s2",
    "tanggal_bergabung": "2023-05-24",
    "outlet": "6",
    "jabatan": "Section Head of IT",
    "divisi": "IT",
    "url_foto": "ff.jpg"
}]

To display this response in your view, you can loop through the response data in your success function and dynamically populate the "Karyawan" select options. However, I can't provide the exact code for that without more context on how your view is structured and how you want to update the options.

英文:

I'm trying to filter my select option with other select option using jquery post, where if certain outlet is selected, the the next select option whic is karyawan will only display karyawan that assign to that outlet, but i don't know to handle the response i get from controller, can anyone help me?

this my view

&lt;div class=&quot;form-group&quot;&gt;
    &lt;label class=&quot;control-label col-md-3 col-sm-3 col-xs-12&quot;&gt;Outlet&lt;/label&gt;
    &lt;div class=&quot;col-md-9 col-sm-9 col-xs-12&quot;&gt;
        &lt;select class=&quot;form-control&quot; name=&quot;outlet&quot; id=&quot;outletSelect&quot;&gt;
            &lt;option value=&quot;&quot;&gt;Choose option&lt;/option&gt;
            @foreach($outlets as $it)
            &lt;option value=&quot;{{$it-&gt;id}}&quot;&gt;{{$it-&gt;nama}}&lt;/option&gt;
            @endforeach
        &lt;/select&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
    &lt;label class=&quot;control-label col-md-3 col-sm-3 col-xs-12&quot;&gt;Karyawan&lt;/label&gt;
    &lt;div class=&quot;col-md-9 col-sm-9 col-xs-12&quot;&gt;
        &lt;select class=&quot;form-control&quot; name=&quot;nama&quot;&gt;
            @if (isset($kritems))
            @foreach($kritems as $its)
            &lt;option value=&quot;{{$its-&gt;nama}}&quot;&gt;{{$its-&gt;nama}}&lt;/option&gt;
            @endforeach
            @endif
        &lt;/select&gt;
    &lt;/div&gt;
&lt;/div&gt;

this is my script

$(document).ready(function() {
    $(&#39;#outletSelect&#39;).change(function() {
      var selectedOutlet = $(this).val(); 
      var token = &quot;{{ csrf_token() }}&quot;;
      $.ajax({
        url: &quot;{{ route(&#39;nilai.choose&#39;) }}&quot;,
        method: &#39;POST&#39;,
        data: { outlet: selectedOutlet,
              &#39;_token&#39;: token, },
        success: function(response) {
            console.log(response);
        },
        error: function() {
          alert(&#39;Failed to fetch karyawan.&#39;);
        }
      });
    });
  });

and this is my controller

public function choose(Request $request)
    {
        $outlet = Outlet::findorfail($request-&gt;outlet);
        $outlets = Outlet::all();
        $kritems = Karyawan::where(&#39;outlet&#39;, $request-&gt;outlet)-&gt;get();

        return $kritems;
    }

and this is the response i get

[{&quot;id&quot;:2,&quot;created_at&quot;:&quot;2023-05-31T08:36:33.000000Z&quot;,&quot;updated_at&quot;:&quot;2023-05-31T08:48:18.000000Z&quot;,&quot;user_id&quot;:18,&quot;nama&quot;:&quot;Hidayat&quot;,&quot;nik&quot;:&quot;3376012705950002&quot;,&quot;nomor&quot;:&quot;333444&quot;,&quot;alamat&quot;:&quot;jlnjlm&quot;,&quot;email&quot;:&quot;dayat@test.com&quot;,&quot;pendidikan&quot;:&quot;s2&quot;,&quot;tanggal_bergabung&quot;:&quot;2023-05-24&quot;,&quot;outlet&quot;:&quot;6&quot;,&quot;jabatan&quot;:&quot;Section Head of IT&quot;,&quot;divisi&quot;:&quot;IT&quot;,&quot;url_foto&quot;:&quot;ff.jpg&quot;}]

but I don't know how to display it to my view

答案1

得分: 1

首先,为了进一步使用,将id分配给select元素,例如karyawan,如下所示:

<select class="form-control" name="nama" id="karyawan"> ....

然后,在您的ajax response() 函数中,渲染所有选项如下:

$(document).ready(function() {
  $('#outletSelect').change(function() {
    var selectedOutlet = $(this).val(); 
    var token = "{{ csrf_token() }}";
    $.ajax({
      url: "{{ route('nilai.choose') }}",
      method: 'POST',
      data: { outlet: selectedOutlet, '_token': token },
      success: function(response) {
         // 获取我们要渲染的元素,然后清空它并渲染选项。
          let karyawan = $("#karyawan");
          karyawan.empty();
          response.forEach(val => {
            karyawan.append(`<option value="${val.nama}">${val.nama}</option>`);
          });
      },
      error: function() {
        alert('无法获取员工信息。');
      }
    });
  });
});
英文:

So first of all give the id to select element for further use such as karyawan like this,

 &lt;select class=&quot;form-control&quot; name=&quot;nama&quot; id=&quot;karyawan&quot;&gt; ....

Then in your ajax response() function, render all the options like this,

$(document).ready(function() {
  $(&#39;#outletSelect&#39;).change(function() {
    var selectedOutlet = $(this).val(); 
    var token = &quot;{{ csrf_token() }}&quot;;
    $.ajax({
      url: &quot;{{ route(&#39;nilai.choose&#39;) }}&quot;,
      method: &#39;POST&#39;,
      data: { outlet: selectedOutlet,
            &#39;_token&#39;: token, },
      success: function(response) {
         // grab the elemtent to where we have to render,then make it empty and render the options.
          let karyawan = $(&quot;#karyawan&quot;);
          karyawan.empty();
          response.forEach(val =&gt; {
            karyawan.append(`&lt;option value=&quot;${val.nama}&quot;&gt;${val.nama}&lt;/option&gt;`);
          });
      },
      error: function() {
        alert(&#39;Failed to fetch karyawan.&#39;);
      }
    });
  });
});

huangapple
  • 本文由 发表于 2023年6月2日 12:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定