2016-11-28 114 views
0

我已經存儲在會話中的購物車,我想刷新會話無需重新加載頁面 我已經試過這樣: 查看:Laravel阿賈克斯內部servor 500(內部服務器錯誤)

<a href="#" id="product" data-id="{{ $product->id }}" class="item_add single-item hvr-outline-out button2">Add to cart</a> 

<script> 
$(document).ready(function() { 
    $('#product').click(function(event) { 
     event.preventDefault(); 

     let url = "{{ route('add-to-cart') }}"; 
     let id = $(this).data('id'); 

     $.ajax({ 
      url: url, 
      type: 'POST', 
      data: {product_id: id, _token: "{{ Session::token() }}"} 
     }) 
     .done(function() { 
      console.log("success"); 
     }) 
     .fail(function() { 
      console.log("error"); 
     }) 
    }); 
}); 

路線:

Route::post('/add-to-cart', '[email protected]')->name('add-to-cart'); 

的ProductsController:

public function addToCart(Request $request) 
{ 
    if ($request::ajax()) { 
     $id = $request->product_id; 

     $product = Product::find($id); 

     if (Session::has('products')) { 
      $products = Session::get('products'); 
      $products[] = $product; 
      Session::put('products', $products); 
     } 

     else { 
      $products = array($product); 
      Session::put('products', $products); 
     } 

     return response()->json(); 
    } 
} 

,當我點擊添加到購物車在控制檯中

+2

檢查你的日誌文件,還有地方在那裏的提示。 – aynber

+0

@aynber在哪裏可以找到該文件? –

+0

storage/logs/laravel.log – Wistar

回答

2

您所訪問的ajax()靜態方法(使用::),即送500(內部服務器錯誤)時,你應該使用->代替:

if ($request->ajax()) { 

使用Laravel日誌文件

正如評論所說,Laravel可能是在告訴你這storage/logs/laravel.log,完成一個長的調用堆棧跟蹤(您提到的行,以「#38」和「#39」開頭)。只需滾動到「#1」之前,你就會找到你的罪魁禍首。

2

Laravel不允許不經過X-CSRF-TOKEN, 以下是我的工作示例希望它可以幫助你。

路線:

Route::post('block-user','[email protected]'); 

現在,你需要在 blade.php您的AJAX調用之前添加AJAX設置這樣:

在頭部添加這個

<meta name="csrf-token" content="{{ csrf_token() }}" /> 

我的腳本,如:

<script> 
//Ajax setup 
    $.ajaxSetup({ 
     headers: { 
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
     } 
    }); 

//Ajax call 

    $(".blockuser").bootstrapSwitch(); 
    $('.blockuser').on('switchChange.bootstrapSwitch', function() { 
     var userid = $('#userid').val(); 
     $.ajax({ 
      url:'/block-user', 
      data:{user_id : userid}, 
      type:'post', 
      success: function(data){ 
       alert(data); 
      } 
     }); 
    }); 
</script> 

控制器:

public function BlockUser(Request $request) 
{ 
    $userid = $request->get('user_id'); 
//perform operation 
}