Jul 19, 2023
0
Level 1
Async Js and Session Laravel with Laragone
Hi Everyone hope you are doing well i am facing issue that i am store items into cart when i store cart item single click until the response is 200 it work fine when i store cart items in multiple clicks it store item only first click item
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// set booking cart item
async function setCartItemIntoSession(cart_items) {
let url = "{{ route('hotel.add.to.cart') }}";
try {
const responses = await Promise.all(
cart_items.map((item) =>
$.ajax({
url: url,
type: "POST",
data: {
cart_items: [item], // Send each cart item individually in an array
},
})
)
);
// Combine all cart items from different responses into a single array
const cartsData = responses.flatMap((response) => response.hotel_cart.cart_items);
// Clear the previous cart content
var cartContent = '';
if (cartsData.length === 0) {
// If there are no items in the cart, disable checkout button
$('.checkout_btn').prop('disabled', true);
toastr.warning("Your cart is empty.");
} else {
// If there are items in the cart, enable checkout button and display cart items
$('.checkout_btn').prop('disabled', false);
$.each(cartsData, function(index, item) {
var bookingCode = item.bookingCode.replaceAll('!', '');
const formattedPrice = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: `${item.currency}`
}).format(item.price);
appendCartItems(bookingCode, formattedPrice, item);
});
var activityGrandTotal = parseFloat(responses[0].activity_grand_total) || 0;
var hotelCartTotal = parseFloat(responses[0].cart_total_hotel) || 0;
// Calculate the total sum for all responses
for (let i = 1; i < responses.length; i++) {
activityGrandTotal += parseFloat(responses[i].activity_grand_total) || 0;
hotelCartTotal += parseFloat(responses[i].cart_total_hotel) || 0;
}
var sum = activityGrandTotal + hotelCartTotal;
var sumWithComma = new Intl.NumberFormat('en-US').format(sum);
$('#sum_values').text(sumWithComma);
toastr.success("You need to book your room within the 30 minutes");
}
// cart count (assuming 'cart_count' is the same for all responses)
$('#cartNotification').text(responses[0].cart_count);
} catch (error) {
// Handle any errors that occurred during the AJAX request
console.error('Error:', error);
}
}
// add to cart hotel rooms
async function addTocart(bookingCode, add_to_cart_button_span, vat) {
var cartSpan = $(`.${add_to_cart_button_span}`);
var addToCartDisabled = $(`#addToCart${add_to_cart_button_span}`);
var addToCartButton = $(`#${add_to_cart_button_span}`);
addToCartDisabled.attr('disabled', true);
cartSpan.addClass('spinner-border');
addToCartButton.html('please wait...');
try {
const response = await $.ajax({
url: '/preBooking',
method: 'POST',
data: {
'bookingCode': bookingCode,
}
});
const hotels = response.hotels;
console.log(hotels, "hotel response");
if (hotels) {
let searchData = @json($recentData);
console.log(searchData, "Hellow");
let hotelCart = hotels.map(item => ({
'bookingCode': bookingCode,
'hotelCode': item.hotelCode,
'hotelName': item.hotelName,
'image': item.mainImage,
'price': item.rooms[0].totalFare,
'currency': item.currency,
'isRefundable': item.rooms[0].isRefundable,
'room': item.rooms[0].name,
'countryCode': searchData['guest_nationality'],
'total_pax': searchData['paxRooms'],
'check_in': searchData['check_in'],
'check_out': searchData['check_out'],
'vat': vat,
}));
console.log(hotelCart, "Cart");
// Do something with the hotelCart array
await setCartItemIntoSession(hotelCart);
} else {
toastr.error("Room alreay booked");
}
} catch (error) {
// Handle any errors that occurred during the AJAX request
console.error('Error:', error);
} finally {
addToCartDisabled.attr('disabled', false);
cartSpan.removeClass('spinner-border');
addToCartButton.html('Add to cart');
}
}
</script>
public function hotelCartSession($request, $activityCart)
{
$cartItems = $request->cart_items;
$bookingCode = $cartItems[0]['bookingCode'];
$totalPrice = 0;
$totalVat = 0;
$bookingCodeExists = false;
if (isset($activityCart['hotel_cart'])) {
foreach ($activityCart['hotel_cart']['cart_items'] as $key => $item) {
if ($item['bookingCode'] === $bookingCode) {
$bookingCodeExists = true;
// Update the existing cart item
$activityCart['hotel_cart']['cart_items'][$key] = $cartItems[0];
break;
}
$totalPrice += floatval($item['price']);
$totalVat += floatval($item['vat']);
}
}
if (!$bookingCodeExists) {
// Add a new cart item
$activityCart['hotel_cart']['cart_items'][] = $cartItems[0];
// Add the price of the new cart item
$totalPrice += floatval($cartItems[0]['price']);
}
$activityCart['hotel_cart'] = [
'cart_items' => $activityCart['hotel_cart']['cart_items'] ?? $cartItems,
];
$activityCart['cart_count'] = isset($activityCart['cart_count'])
? $activityCart['cart_count'] + count($cartItems)
: count($cartItems);
$activityCart['cart_total_hotel'] = $totalPrice;
$activityCart['cart_totalVat_hotel'] = $totalVat;
session(['activity_cart' => $activityCart]);
return $activityCart;
}
Please or to participate in this conversation.