2016-10-01 53 views
0

我使用laravel 4,我想用ajax發送到控制器的請求,當我點擊鏈接:內部服務器錯誤阿賈克斯Laravel

HTML:

<a class='btn btn-primary signup ' id="btnDialog" 
onClick='ajouter({{$data->id_facture}});'> Ajouter à la lise de paiement</a> 

但我總是得到錯誤柱500(內部服務器錯誤)

的javascript:

<script type="text/javascript"> 

function ajouter(id){ 

    $.ajax({ 

     url:'/ajouter/'+id, 
     dataType: 'JSON', 
     type: 'post', 

     success:function(data){ 

     if(data == 'ok'){ 
      alert('added to the list'); 
     } else { 
      alert('error'); 
     } 
    } 
    }); 
    return false; 
} 

</script> 

控制器:

public function ajouter($id=0){ 

    //return json_encode('ok'); 
    if($facture = Facture::find($id)) 
    { 
     $item = new List($id); 
     Session::put('list',$item); 
     return json_encode('ok'); 
    } 
    else 
     return json_encode('error'); 
} 

順便說一句,我做了下面的代碼一個簡單的測試,它的工作:

的javascript:

<script type="text/javascript"> 

function ajouter(id){ 

    $.ajax({ 

     url:'/ajouter/'+id, 
     dataType: 'JSON', 
     type: 'post', 

     success:function(data){ 

      console.log(data); 
     } 
    }); 

    return false; 
} 

</script> 

控制器:

public function ajouter($id=0) 
{ 
    return json_encode('ok'); 
} 
+0

嘗試檢查你得到你的500種狀態是什麼錯誤。也許它會幫助你認識到什麼是問題。您可以在瀏覽器中的開發人員工具的Network選項卡的幫助下做到這一點 – Silwerclaw

+0

在您的'ajax'中,您在'url'中傳遞了id,但是我看不到您在控制器中獲得了該Id,所以當您正試圖取得你的紀錄,這將不會成功。 – Franco

回答

0

你的Ajax請求

$.ajax({ 
    url: '/ajouter',  
    type: 'GET', 
    data: "id=" + id, 
    dataType: "JSON", 
    success: function(data, textStatus, jqXHR) 
    { 
    if(data !="") 
    {    
     console.log(data);    
    } 

    }, 
    error: function(jqXHR, textStatus, errorThrown) 
    {    
    //alert(); 
    } 
}); 

這是你的控制器

public function getAjouter() 
{ 
    $id = Input::get('id'); 
    $facture = Facture::find($id); 
    if(count($facture) > 0) 
    { 
    $item = new List($id); 
    Session::put('list', $item); 
    return json_encode('ok'); 
    } 
    else { 
    return Response::json(array('error' => 'Error message'), 401); 
    } 
}