I am trying to update the value of a boolean database field (is_active) in a blade template by toggling a checkbox input, in a form using Bootstrap 4 Toggle. This adds some additional elements which I can successfully reference using on('click').
I've got this working without ajax but am struggling to workout a solution with what I've got so far:
form.blade.php
<form action="{{route('user.profile.user-active')}}" method="POST" class="user-active">
@csrf
<input type="checkbox" name="is_active" value="1" @if(!Auth::user()->profile->is_active) checked @endif data-toggle="toggle" data-on="Yes" data-off="No">
<input type="hidden" name="profile_id" value="{{Auth::user()->profile->id}}">
<button type="submit">submit</button>
</form>
What form.blade.php looks like with Bootstrap 4 Toggle:
<form action="http://localhost:8000/user/profile/user-active" method="POST" class="user-active">
<input type="hidden" name="_token" value="IjHbGDJlE3AXZZOjTstPL2x976DlhHXoK5TVeBOi">
<div class="toggle btn btn-light off" data-toggle="toggle" role="button" style="width: 61.5938px; height: 38px;">
<input type="checkbox" name="is_active" value="1" checked="" data-toggle="toggle" data-on="Yes" data-off="No">
<div class="toggle-group">
<label for="" class="btn btn-primary toggle-on">Yes</label>
<label for="" class="btn btn-light toggle-off">No</label>
<span class="toggle-handle btn btn-light"></span>
</div>
</div>
<input type="hidden" name="profile_id" value="1">
<button type="" submit="">submit</button>
</form>
non ajax, working controller method - ProfileController.php
public function changeUserActiveStatus(Request $request){
$profile = Profile::findOrFail($request->profile_id);
$profile->is_active = $request->is_active == 1 ? 0 : 1;
$profile->save();
return redirect()->back();
}
jQuery:
<script>
$(function (){
$('form.user-active .toggle').on('click', function (event) {
$.ajax({
type: 'POST',
url: "{{route('user.profile.user-active')}}",
});
});
});
</script>
I realise that the jQuery is not complete and I'm kind of at the limit of my skills in this area although I'm researching, googling my way through, looking at comparable examples that solve this problem etc but not getting very far at the moment.