我正在尝试切换一个开关,将我的数据库状态设置为0或1.我正在使用ajax请求但是当我尝试切换时没有任何反应。我做得不对吗?
我已经包含了更新,但没有任何反应,我的控制台也没有错误。我做对了吗?
控制器
public function updateFlag()
{
if(Request::ajax())
{
$auto_reply = Toggle::where('id', Auth::user()->id)->first();
if($auto_reply->status == 0)
{
$auto_reply->status = 1;
$auto_reply->save();
}
else{
$auto_reply->status = 0;
$auto_reply->save();
}
}
}
HTML
<div class="container ">
<input checked data-toggle="toggle" data-on="Enabled" data-off="Disabled" name="auto_reply" type="checkbox">
</div>
JS
<script>
$("[name='auto_reply']").bootstrapSwitch();
$(document).ready(function() {
$("[name='auto_reply']").on('switchChange.bootstrapSwitch',function(){
$.ajax({
url: '/admin/dashboard/status/update',
method: 'post',
success: function(data){
alert("Auto Reply has been Turned On");
},
error: function(){
alert("Auto Reply has failed");
}
});
});
});
</script>
路线
Route::post('admin/dashboard/status/update', 'StatusController@updateFlag');
更新
<script>
$(document).ready(function() {
$("[name='auto_reply']").on('switchChange.bootstrapSwitch',function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: '/admin/dashboard/status/update',
method: 'post',
success: function(data){
alert("Auto Reply has been Turned: "+data.msg);
},
error: function(){
alert("Auto Reply has failed");
}
});
});
});
</script>
错误日志
[
2017-11-19 19:48:23] local.ERROR: Non-static method Illuminate\Http\Request::ajax() should not be called statically {"userId":1,"email":"data@gmail.com","exception":"[object] (ErrorException(code: 0): Non-static method Illuminate\\Http\\Request::ajax() should not be called statically at /Users/emmnock/FastFoodOderSystem/app/Http/Controllers/Admin/LoyaltyController.php:70)
[stacktrace]
#0 /Users/emmnock/FastFoodOderSystem/app/Http/Controllers/Admin/LoyaltyController.php(70): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(8192, 'Non-static meth...', '/Users/emmnock/...', 70, Array)
#1 [internal function]: App\\Http\\Controllers\\Admin\\LoyaltyController->updateFlag()
#2 /Users/emmnock/FastFoodOderSystem/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)
#3 /Users/emmnock/FastFoodOderSystem/vendor/laravel/framework/src/Illuminate/R
outing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction('updateFlag', Array)
答案 0 :(得分:0)
试试这个......
public function updateFlag(Request $request)
{
if($request->ajax())
{
$auto_reply = Toggle::where('id', Auth::user()->id)->first();
if($auto_reply->status == 0)
{
$auto_reply->status = 1;
$auto_reply->save();
}
else{
$auto_reply->status = 0;
$auto_reply->save();
}
}
}