stephen waweru's avatar

status of 500 (Internal Server Error) in ajax request laravel 8

I want to show the price of an item based on the size a user selects. am using ajax to achieve this, but when I run the request it responds with a status of 500 (Internal Server Error) error in the console and also in the browser it skips the success function and runs the error function thus displaying an alert error.i haven't understood where have gone wrong with my code.have a look

here is my blade file which shows the size and prices

<div class="ps-product__meta">
     <span id="getattrprice" class="ps-product__price sale">{{ $products->merch_price }</span>
     <span class="ps-product__del">{{ $products->merch_splprice }}</span>
<div class="ps-product__group">
 <h6>Size</h6>
  <div class="input-group mb-3">
    <select class="custom-select" product-id="{{ $products['id'] }}" 
      id="getprice" name="productsize">
      <option value="">Select Size</option>
        @foreach ($products->merchadiseattributes as $attribute )
           <option value="{{ $attribute->productattr_size }}">{{ $attribute- 
             >productattr_size }} 
           </option>
        @endforeach
    </select>
</div>

the jquery script

$.ajaxSetup({
    headers:{
        'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    }
});
$(document).ready(function(){
    $('#getprice').change(function(){
        var productsize=$(this).val();
        if(productsize==""){
            alert("please Select size");
            return false;
        }
        var product_id=$(this).attr("product-id");
        // alert(product_id);
        $.ajax({
            url:'/getproductprice',
            data:{productsize:productsize,product_id:product_id},
            type:'POST',
            success:function(resp){
                // alert(resp);
                $("#getattrprice").html(+resp);
            },error:function(){
                alert("Error");
            }
        });
    });
});

the getproductprice method in the controller

public function getproductprice(Request $request)
{
  if($request->ajax()){
    $data=$request->all();
    // echo "<pre>";print_r($data);die;
    $getproductprice=Productattribute::where(['product_id'=>$data['product_id'],
     'productattr_size'=>$data['productattr_size']])
            ->first();
            return $getproductprice->productattr_price;
        }
     }

**the route**

Route::post('/getproductprice', [Home_controller::class,'getproductprice'])->name('getproductprice');
0 likes
15 replies
stephen waweru's avatar

@frankielee i have edited the code to this but still it doesn't work out $getproductprice = DB::table('productattributes')->where( ['product_id'=>$data['product_id']], ['productattr_size'=>$data['productattr_size']], )->get();

frankielee's avatar

So what is the error shows in the log file? Also, please format your code.

You are using the correct model Productattribute? Not following the Laravel's pattern?

Productattribute::where([
		['product_id'=>$data['product_id'],
		['productattr_size'=>$data['productattr_size']
])->first();
frankielee's avatar

@stephen waweru

So what is the error shows in the log file?

Your Laravel should have the Log file that contains the detail of the error.

stephen waweru's avatar

@frankielee this is the log error [2021-11-08 10:00:41] local.ERROR: Property [productattr_price] does not exist on this collection instance. {"exception":"[object] (Exception(code: 0): Property [productattr_price] does not exist on this collection instance. at F:\Main Server\htdocs\voskillproject\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php:905) [stacktrace]

frankielee's avatar

@stephen waweru Use first()

Check my codes

Productattribute::where([
		['product_id'=>$data['product_id'],
		['productattr_size'=>$data['productattr_size']
])->first();
Sergiu17's avatar

Here's what to send to the server

data:{productsize:productsize,product_id:product_id}

Here's what to trying to access on PHP side

['product_id' => $data['product_id'], 'productattr_size' => $data['productattr_size']]

You don't have productattr_size inside request,

Should be:

['product_id' => $data['product_id'], 'productattr_size' => $data['productsize']]
stephen waweru's avatar

i have researched more and more and found a solution clearer code that explain the logic. I have edited the getproductprice method to this

  $getproductprice = DB::table('productattributes')->where(
            ['product_id'=>$data['product_id']],
            ['productattr_size'=>$data['productsize']],
        )->first(); 
        return response()->json($getproductprice->productattr_price);

and it responds by showing only one price for all the attributes..how can I fix this to show price per size

Sergiu17's avatar

Instead of ->first() use ->get, it will return a collection and you have to iterate over it and print every price, you can do this inside controller or you can adjust your JS script to do this

2 likes
stephen waweru's avatar

@Sergiu17 thanks alot..the code works very well...how can I adjust it in the js script to show the price per size? i have tried this but the code returns an error return response()->json($getproductprice->productattr_price);

Sergiu17's avatar

not sure what's the exact structure of your html, but here's a basic example

success: function(resp) {
  $.each(resp, function(k, v) {
    $("#getattrprice").appent(v.productattr_price);
  });
}

something like this, open network tab and see what's the response you get

stephen waweru's avatar

@Sergiu17 here's how my price html code looks like Sh.{{ $products->merch_price }}

the $products code reads the original set price in the merchandise table which I set when entering data which also is the price for the small attribute...on selecting any of the values I the dropdowns it shows sh.[object Object],[object Object],[object Object],[object Object] in the price part,I guess this means it shows all the prices for all the attributes.what am now trying to achieve is to get the price for each attribute and display it on the browser

Please or to participate in this conversation.