Laravel-使用复选框和Ajax切换数据库中的值 [英] Laravel - Toggle value in database with checkbox and ajax
本文介绍了Laravel-使用复选框和Ajax切换数据库中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过jquery和ajax的复选框来切换表中的布尔值.
I want to toggle a boolean value in my table with a checkbox through jquery and 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){
}
});
});
});
推荐答案
我唯一要修改的就是返回ajax调用的答案,让它知道发生了什么.
The only thing I'd modify would be returning an answer to the ajax call to let it know what's happening.
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
}
}
});
});
});
这篇关于Laravel-使用复选框和Ajax切换数据库中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文