0
我試圖更新或插入我的數據庫表(user_shows),每當我點擊一個鏈接而不去另一個頁面。所以,我用Ajax和下面是我的代碼: JQuery Ajax Post導致500內部服務器錯誤(使用Laravel 5.1)
$("#fave").click(function(){
var url = $(this).attr("data-link");
var data = {
_token: $(this).data('token'),
id: $(this).attr("name")
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/addFavorites",
type:"post",
data: data,
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
</script>
對於HTML:
<a id="fave" name="{{ $query[0]->tvSeriesID }}" href="#" data-link="{{ url('/addFavorites') }}" data-token="{{ csrf_token() }}" title="Mark this TV show a favorite!"><span class="glyphicon glyphicon-star" aria-hidden="true"></span> Favorites</a>
對於路線:
Route::post('/addFavorites', function() {
$id = Input::get('id');
$data = $id;
return $data;
});
輸出:取數據是正確的 enter image description here
但是當我在我的路線中放一些代碼時,我得到了P OST http://localhost:8000/addFavorites 500(內部服務器錯誤)
這是我的新航線代碼
Route::post('/addFavorites', function() {
$id = Input::get('id');
$query = DB::table('user_shows')
->where('tvSeriesID', '=', $id)
->where('userID', '=', Auth::id())
->get(['favorite']);
if(empty($query))
{
//saving to DB
$faves = new UserShow;
$faves->tvSeriesID = $id;
$faves->userID = Auth::id();
$faves->favorite = 1;
$faves->save();
$data = "Show is added to Favorites";
return $data;
}
else
{
if($query[0]->favorite == 1) {
$data = "Show is already in Favorites";
}
else {
UserShow::where('tvSeriesID', $id)
->where('userID', Auth::id())
->update(['favorite' => 1]);
$data = "Show is added to Favorites";
}
$data = "Show is added to Favorites";
return $data;
}
});
是我的編碼錯誤的?希望您能夠幫助我。提前致謝。
AJAX不會導致它,它是你正在發送哪個導致錯誤。 –
您是否在瀏覽器控制檯中觀看過AJAX請求/響應? –
當我使用第一個路由代碼時,我正在發送的數據正在被提取,當我嘗試添加一些代碼時,它會導致錯誤? @JayBlanchard – prinx04