I am creating an E-commerce web application In frontend I am using a template and in backend I am using Laravel 8, I need to post AddToCart data with ajax, but when I click AddToCar button I get and error
'Uncaught TypeError: a.getElementsByClassName is not a function'
My button
<button type="submit" class="btn btn-primary mb-2" onclick="addToCart">Add to Cart</button>
Ajax code
//Start Add to Cart Product
function addToCart(){
var product_name = $('#pname').text();
var id =$('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity =$('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url:"/cart/data/store/"+id,
success:function(data){
console.log(data);
}
})
}
My controller
public function AddToCart(Request $request, $id){
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->selling_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}else{
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->discount_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}
}
First of all, there are some things we can get better on the function like using const instead of var and not defining two times the variable on the object as they have the same name.
function addToCart() {
const id = $('#product_id').val();
const product_name = $('#pname').text();
const color = $('#color option:selected').text();
const size = $('#size option:selected').text();
const quantity = $('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data: {
color, size, quantity, product_name,
},
url: `"/cart/data/store/"${id}`,
success: console.log
});
}
Anyways, your main issue is an error that is not related or visible in your code as you are using a library/framework (in this case, seems like jquery). You gotta check the stacktrace to see what part of YOUR code is triggering the error. Maybe is not even on this snippets you're sharing here.