How to pass a variable from view to controller using javascript on change in laravel

I want to passing a variable (id) from view to controller using javascript onChange. I have done it but the result when I'm do dd always the same. In my case i always get "7".

Here is my code:

View:

 <select id="jurusan_id" type="text" name="jurusan_id" onchange="filterJurusan()">
       <option value disable>Jurusan</option>
         @foreach (App\Models\Admin\Jurusan::all() as $jurusan)
          <option value="{{ $jurusan->id }}">{{ $jurusan->nama_jurusan }}</option>
         @endforeach
    </select>

Route:

 Route::get('datasiswa/{id}', 'Admin\SiswaController@filterSiswa')->name('filterSiswa');

Js:

function filterJurusan() {
  window.location.href = "{{ route('filterSiswa', $jurusan->id) }}";
}

Controller:

public function filterSiswa(Request $request, $id)
  {
      dd($id);
  }

I know something was wrong with my code, but i can't figure out what it is.


Solution 1:

I think you are confusing server-side and client-side code. The JS code piece renders the route once upon loading. The $jurusan variable is set to the last object of your foreach loop. Therefore the id will always be 7.

You will have to get the selected item. For that adjust the onchange function:

onchange="filterJurusan(this)"

Afterwards you can get the value, which is the id like this.

function filterJurusan(el) {
 var value = (el.value || el.options[el.selectedIndex].value); 
  window.location.href = '/datasiswa/'+value;
}

Now the question is if you simply want to change the location (like in the code) or as your function names indicate, want to filter data?

Solution 2:

Actually, you are populating Jurusan records on view by App\Models\Admin\Jurusan::all() as $jurusan. What this does is populate options in your select but at the end of iterations last record's data left stored in $jurusan variable that you are using in function filterJurusan() to call controller method. You should get jurusanId = document.getElementById('jurusan_id') and pass it to the controller like window.location.href = '/datasiswa/' + jurusanId;