Reputation: 2505
I have build a shopping cart..Where I tried to update database using ajax..when I will update the quantity, it will reflect the database immediately..
for that i used the following View:
@foreach($carts as $row)
<input type="hidden" class="cat_id" value="{{$row->id}}"/>
<input type="number" class="quantity" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> ×${{$row->p_price}}
@endforeach
Here is the Ajax Part:
$(".quantity").change(updateCart);
function updateCart(){
var qty = parseInt($(this).val());
var cat_id = parseInt($('.cat_id').val());
console.log(cat_id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"{{url('cart/update/{cat_id}/{qty}')}}",
method:"POST",
data:{cat_id:cat_id, qty:qty},
success: function( data ) {
// console.log(data);
}
});
}
Route
Route::post('cart/update/{cat_id}/{qty}','ProductController@cartUpdate');
And the controller part :
public function cartUpdate($cat_id, $qty)
{
$cart = Cart::find($cat_id);
$product = Product::find($cart->product_id);
$cart->no_of_items = Input::get('qty');
$cart->price = $product->price * $cart->no_of_items;
$cart->save();
}
I have product_id in carts table The problem I'm facing is whenever i tried to update the Quantity i saw error on console mode:
ErrorException in ProductController.php Trying to get property of non-object
when i dd() the cat_id i see null value or same for all the curt..what could be the possible? thanks
Upvotes: 1
Views: 20590
Reputation: 119
Try This Way:
@foreach($carts as $row)
<input type="hidden" class="cat_id" name="cat_id" value="{{$row->id}}"/>
<!--Add name="cat_id" AS Attribute -->
<input type="number" class="quantity{{$row->id}}" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> ×${{$row->p_price}}
@endforeach
And Ajax Part :
@foreach($carts as $row)
$(".quantity{{$row->id}}").change(updateCart);
@endforeach
function updateCart(){
var qty = parseInt($(this).val());
var cat_id = parseInt($('.cat_id').val());
console.log(cat_id);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:'cart/update',
method:"POST",
data:{
cat_id:cat_id,
qty:qty
},
success: function( data ) {
// console.log(data);
}
});
}
Upvotes: 1
Reputation: 7972
The issue is you are not passing the cat_id
and qty
via the url and is passed via ajax post request
$.ajax({ url:"{{url('cart/update/{cat_id}/{qty}')}}", method:"POST", data:{ cat_id : cat_id, qty: qty }, success: function( data ) { // console.log(data); } });
hence the $cat_id
and $qty
is null
in the Controller, so you need to change the code in your controller as
public function cartUpdate($cat_id, $qty) { $cart = Cart::find(Input::get('cat_id')); $product = Product::find($cart->product_id); $cart->no_of_items = Input::get('qty'); $cart->price = $product->price * $cart->no_of_items; $cart->save(); }
Upvotes: 3