I'm trying to submit data via ajax (add to cart) but got an error in console POST http://localhost/glutax9gs/cartupdate 500 (Internal Server Error)
What's wrong with my code? Is it the javascript or the controller?
here is my Route:
Route::get('/cartupdate', 'FrontEndController@cartupdate')->name('update.cart');
Route::post('/cartupdate', 'FrontEndController@cartupdate')->name('cart.update');
Controller code is here:
public function cartupdate(Request $request)
{
if ($request->isMethod('post')){
if (empty(Session::get('uniqueid'))){
$cart = new Cart;
$cart->fill($request->all());
Session::put('uniqueid', $request->uniqueid);
$cart->save();
}else{
$cart = Cart::where('uniqueid',$request->uniqueid)
->where('product',$request->product)->first();
//$carts = Cart::where('uniqueid',$request->uniqueid)
//->where('product',$request->product)->count();
if (count($cart) > 0 ){
$data = $request->all();
$cart->update($data);
}else{
$cart = new Cart;
$cart->fill($request->all());
$cart->save();
}
}
return response()->json(['response' => 'Successfully Added to Cart.','product' => $request->product]);
}
$getcart = Cart::where('uniqueid',Session::get('uniqueid'))->get();
return response()->json(['response' => $getcart]);
}
jQuery code is here:
$(".to-cart").click(function(){
var formData = $(this).parents('form:first').serializeArray();
$.ajax({
type: "POST",
url: '',
data:formData,
success: function (data) {
getCart();
$.notify(data.response, "success");
},
error: function (data) {
console.log('Error:', data);
}
});
});
View code is here:
<form>
<p>
@if(Session::has('uniqueid'))
<input type="hidden" name="uniqueid" value="">
@else
<input type="hidden" name="uniqueid" value="">
@endif
<input type="hidden" name="title" value="">
<input type="hidden" name="product" value="">
<input type="hidden" id="cost" name="cost" value="">
<input type="hidden" id="quantity" name="quantity" value="1">
@if($product->stock != 0 || $product->stock === null )
<button type="button" class="button style-10 to-cart">Add to cart</button>
@else
<button type="button" class="button style-10 to-cart" disabled>Out Of Stock</button>
@endif
</p>
</form>
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire