[英]Laravel - Toggle value in database with checkbox and ajax
I want to toggle a boolean value in my table with a checkbox through jquery and ajax.我想通过 jquery 和 ajax 使用复选框切换表中的布尔值。
So whenever a user ticks the the checkbox it should toggle the value in table.因此,每当用户勾选复选框时,它应该切换表中的值。
So far i came up with this but i need help:到目前为止,我想出了这个,但我需要帮助:
$(document).ready(function(){
$("input:checkbox").change(function() {
var isChecked = $("input:checkbox").is(":checked") ? 1:0;
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: $('.checkbox').serialize(),
success:function(data){
}
});
});
});
The only thing I'd modify would be returning an answer to the ajax call to let it know what's happening.我唯一要修改的就是返回 ajax 调用的答案,让它知道发生了什么。
public function activation(Request $request)
{
$user = User::findOrFail($request->user_id);
if($user->active == 1){
$user->active = 0;
} else {
$user->active = 1;
}
return response()->json([
'data' => [
'success' => $user->save(),
]
]);
}
And now in the front-end part:
$(document).ready(function(){
$("input:checkbox").change(function() {
var user_id = $(this).closest('tr').attr('id');
$.ajax({
type:'POST',
url:'/activation',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "user_id" : user_id },
success: function(data){
if(data.data.success){
//do something
}
}
});
});
});
function toggleActive ()
{
$this->active!=$this->active;
return $this;
}
in controller 在控制器中
$model->toggleActive()->save();
in model create a method在模型中创建一个方法
function toggleActive ()
{
$this->active!=(int)$this->active;
return $this;
}
in controller在控制器中
$model->toggleActive()->save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.