my fellow problem solvers. Hopefully, you have a productive day. I am working on an e-commerce website project whereby I do it by using Laravel 8. So far I have reached a point to create 'add to cart' so as customers could do shopping. By reading different tutorials I am grateful that I can add products to the cart, edit and update them also deleting. But I want it to work without refreshing the page. I used Jquery to create Ajax requests as a lot of tutorials suggested. I think it will be simple for you to understand and help if I will show my codes.
here is my 'add to cart' link
<li class="add_to_cart"><a href="javascript:void(0)" data-tippy="Add to cart" onclick="addtocart(<?php echo $product->productID ?>)" data-tippy-placement="top" data-tippy-arrow="true" data-tippy-inertia="true"> <span class="lnr lnr-cart"></span></a></li>
Here is Ajax and Jquery
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function quickview(id) {
$.get('/quickview/'+id, function (response) {
if (response) {
$("#id").html(response.id);
$("#brand").html(response.brand);
$("#productname").html(response.product_name);
$("#price").html(response.price);
$("#description").html(response.product_context);
$("#img").attr('src',response.image);
}
})
}
function addtocart(id) {
var _url = '/product/add-to-cart/'+id;
$.ajax({
url: _url,
method: "GET",
data: {
_token: '{{ csrf_token() }}',
id: id
},
success: function (response) {
window.location.reload();
// I think here is where I stuck,
},
error: function (data) {
console.log('Error:', data);
}
});
}
</script>
Here is my route
Route::get('/product/add-to-cart/{id}', [ProductController::class, 'addToCart'])->name('add.to.cart')->middleware('loggedin');
Here is controller
public function addToCart($id)
{
$product = Product::findOrFail($id);
$cart = session()->get('cart', []);
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
} else {
$cart[$id] = [
"name" => $product->product_name,
"quantity" => 1,
"price" => $product->price,
"maelezo" => $product->product_context,
"image" => $product->image
];
}
session()->put('cart', $cart);
return response()->json(['success' => true]);
// return response()->json($cart);
//return response()->json($cart);
}
My Answer:
a new object in JavaScript without using the `new` keyword?
Yes, you can create a new object in JavaScript using object literal syntax. Here's an example:
javascript
const newObj = {
key1: 'value1',
key2: 'value2'
};
console.log(newObj); // { key1: 'value1', key2: 'value2' }
In this example, `newObj` is created using object literal syntax with key-value pairs. This is a common way to create new objects in JavaScript without using the `new` keyword.
Rate this post
3 of 5 based on 3767 votesComments