簡體   English   中英

jQuery Ajax Post導致500內部服務器錯誤(使用Laravel 5.1)

[英]JQuery Ajax Post results in 500 Internal Server Error (using Laravel 5.1)

每當我單擊一個鏈接而沒有轉到另一個頁面時,我都試圖更新或插入數據庫表(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;
});

輸出:數據提取正確,請在此處輸入圖像描述

但是,當我在路由中放入一些代碼時,我得到了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;
}
});

我的編碼有誤嗎? 希望您能夠幫助我。 提前致謝。

我終於弄清楚了為什么會出錯。 我沒有包含我使用的模型的名稱空間,即UserShow。 當我添加名稱空間時,它起作用了! 這是我使用App \\ UserShow添加的行 非常感謝@Jay Blanchard的快速回復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM