Reputation: 29
I'm currently working on a Laravel project. In the admin view I got Bootstrap Toggle for activating/deactivating users. Everything works well besides the fact that I can't change the checkboxes into a Toggle. When i change class="toggle-class" into data-toggle="toggle", The toggle appears but the data won't be send to the database anymore so the code won't work anymore...
This is what I have
This is what I want
My Admin view
<input id="{{$user->id}}" class="toggle-class"
type="checkbox" data-onstyle="success" data-offstyle="danger"
data-on="Active" data-off="Inactive"
{{ $user->status ? 'checked' : '' }}
onclick="changeStatus(event.target, {{ $user->id }});">
function changeStatus(_this, id) {
var status = $(_this).prop('checked') == true ? 1 : 0;
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '{{route("change.status")}}',
type: 'POST',
data: {
_token: _token,
id: id,
status: status
},
success: function(data){
if (data.type == "error") {
$('#message').html("<div class='alert alert-danger card h2'>"+data.fail+"</div>");}
else {
$('#message').html("<div class='alert alert-success card h2'>"+data.success+"
</div>");
}}
});
}
The method in my controller
public function changeStatus(Request $request)
{
$user = User::find($request->id);
$user->status = $request->status;
$user->save();
return response()->json(['success'=>'Status change successfully.']);
}
Don't know what I'm doing wrong tbh. Can't seem to get it to work.
Upvotes: 1
Views: 1557
Reputation: 45
I have had the same problem as you by replacing the places of inactive and active my problems get solved.
var status = $(this).children().prop('checked') == true ? 'active' : 'inactive';
to this line
var status = $(this).children().prop('checked') == true ? 'inactive' : 'active';
here is my code
< script type = "text/javascript" >
$(document).ready(function() {
$('.toggle').click(function() {
var status = $(this).children().prop('checked') == true ? 'inactive' : 'active';
var id = $(this).children().data('id');
$.ajax({
type: 'POST',
dataType: "json",
url: 'statusUpdate',
data: {
'status': status,
'id': id
},
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
success: function(data) {
Swal.fire(
'GREAT!', 'Status changed successfully', 'success')
location.reload();
console.log(data.success);
}
});
});
}) <
/script>
<input data-id="{{ $catego->id }}" class="toggle-class" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="warning" data-offstyle="dark" type="checkbox" {{ $catego->status == 'active' ? 'checked' : '' }}>
route code// Route::post('statusUpdate', [CategoryCRUDController::class, 'changeStatus']);
// My controller
public function changeStatus(Request $request) {
$category = Category::find($request->id);
$category->status = $request->status;
$category->save();
return response()->json(['success'=>' status change successfully.']); }
Upvotes: 0