如何发送单选按钮值而无需在laravel中提交?

如何发送单选按钮值而无需在laravel中提交?

问题描述:

I want to send the radio button value without submit.

This is the view

enter image description here

This is view code

<table>
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th><center>Presence</center></th>
            </tr>
        </thead>
        <tbody>
                @php
                 $i=1;
                @endphp
            <tr>
                <td>{{$i}}</td>
                <td>TEST</td>
                <td>

                    <input type="radio" id="radio1" name="presence" value="Y">
                    <label for="radio1"><font color="#00B01D"><i class="fas fa-check"></i> Yes</font></label>
                    <input type="radio" id="radio2" name="presence" value="N">
                    <label for="radio2"><font color="#FF0000"><i class="fas fa-times"></i> No</font></label>
                </td>

            </tr>
            @php
                $i++;
            @endphp
        </tbody>
    </table>

<script>  
            $(document).ready(function(){  
                    $('input[type="radio"]').click(function(){  
                        var presence = $(this).val();  
                        $.ajax({  
                            url:"http://localhost/admin/presence/add",  
                            method:"POST",  
                            data:{
                                  presence:presence
                                  },  
                            success:function(data){  

                            }  
                        });  
                    });  
            });  
    </script>  

And this is controller

public function addprespost(Request $request){
        $dataz = [
            'presence' => $request->input('presence'),
        ];
        DB::table('presence')->insert($dataz);
        return redirect('/admin/presence/add');
    }

With my code above, if I click the presence button, there is nothing happen, even I checked in console browser.

I want to make if I press the presence button Yes or No, it'll send the value to the database.

Add hidden token for csrf in your input.

like this

<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="radio" id="radio1" name="presence" value="Y">
<label for="radio1"><font color="#00B01D"><i class="fas fa-check"></i> Yes</font></label>
<input type="radio" id="radio2" name="presence" value="N">
<label for="radio2"><font color="#FF0000"><i class="fas fa-times"></i> No</font></label>

then in your ajax remove the localhost just the route is fine and add the csrf

$.ajax({  
  url:"/admin/presence/add",  
  method:"POST",  
  data:{
   '_token': $('input[name=_token]').val(),
   'presence':presence
  },  
  success:function(data){  

  }  
});  

I don't know if radio have a click event you can also try this one for other option if radio is clicked.

Hope it helps!