2016-03-03 152 views
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; 
} 
}); 

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

+0

AJAX不會導致它,它是你正在發送哪個導致錯誤。 –

+0

您是否在瀏覽器控制檯中觀看過AJAX請求/響應? –

+0

當我使用第一個路由代碼時,我正在發送的數據正在被提取,當我嘗試添加一些代碼時,它會導致錯誤? @JayBlanchard – prinx04

回答

0

我終於明白了錯誤的原因。我沒有包含我使用的UserShow模型的命名空間。當我添加它的命名空間它的工作! 這是我添加的行使用App \ UserShow;。 非常感謝你@Jay Blanchard的快速回復。

相關問題