Home > Software design >  $request->input Returning Null in Laravel
$request->input Returning Null in Laravel

Time:12-29

I want to try if i select a value that is in the "dropdown" it will automatically replace another value in the same page without updating the page, and using ajax, but on the controller part i get the message "request=null" i don't understand even though I have entered the name of the input from "view" to the controller. this is some of my project code

view.blade

<label >Karyawan</label>
<select  id="idSelect" aria-label="Default select example" name="pilih-nama">
  <option value="">-Pilih Karyawan-</option>
   @foreach ($karyawan as $data)
      <option value=" {{$data->nip_kyn}}">{{$data->nama_kyn}}</option>
   @endforeach
</select>

Controller

public function showData(Request $request)
{
    $nip = $request->input('pilih-nama');
    $data = Karyawan::where('nip_kyn', $nip)->first();
    return response()->json(['data' => $data]);
}

Ajax code in main view

    <script>
    $(document).on('change', '.select-name', function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        var hasil = $(this).val();
        // 
        if (hasil == '') {
            document.location.href = "unduhQR";
        }
        $.ajax({
            url: "{{route('showData.index')}}",
            type: 'post',
            data: {
                data: hasil
            },
            success: function(res) {
                console.log(res.data)
                // $('.nama-kar').html(res.data.nama_kyn)
                // $('.idQr').html('NIP : '   res.data.nip_kyn)
            },
            error: function(xhr) {
                // console.log(xhr)
            }
        })
    })
</script>

my route

Route::post('/showQR', [QRCodeController::class, 'showData'])->name('showData.index');

but if i change in my controller like this

    $nip = 'NIP001'; // <-- Value from database
    $data = Karyawan::where('nip_kyn', $nip)->first();
    return response()->json(['data' => $data]);

its going work, but that's not dynamic, any suggestion to solve this guys ?

CodePudding user response:

You need to send the data like this

data: {pilih-nama: hasil}

and to be honest your variable names are not good. You should change them with good ones.

  • Related