JQuery Ajax Post导致500内部服务器错误(使用Laravel 5.1)

时间:2016-03-03 18:21:35

标签: php jquery ajax

每当我点击一个链接而不转到另一个页面时,我正在尝试更新或插入我的数据库表(user_shows)。所以,我使用ajax,下面是我的代码:         

    $("#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

但是当我在我的路线中放入一些代码时,我得到POST 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;
}
});

我的编码错了吗?希望您能够帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我终于弄明白了为什么会出错。我没有包含我使用的模型的命名空间,即UserShow。当我添加命名空间时它起作用了! 这是我添加的行使用App \ UserShow; 。 非常感谢@Jay Blanchard的快速回复。

相关问题