document.addEventListener('DOMContentLoaded', function () { // Create the connection const connection = new signalR.HubConnectionBuilder() .withUrl("/cartHub") .withAutomaticReconnect() .configureLogging(signalR.LogLevel.Error) .build(); // Function to handle cart updates connection.on("ReceiveCartUpdate", function (count) { // Update the cart count display const cartCountElement = document.getElementById("cartCount"); if (cartCountElement) { if (count > 0) { cartCountElement.textContent = count; } else { cartCountElement.textContent = "0"; } } }); // Start the connection connection.start() .then(function () { // console.log("SignalR Connected!"); }) .catch(function (err) { console.error("SignalR Connection Error: " + err.toString()); }); // Optional: Add event listeners for cart operations done via client-side JS // This is if you have any "Add to Cart" buttons that use AJAX document.querySelectorAll('.add-to-cart-button').forEach(button => { button.addEventListener('click', function (e) { // Your existing add-to-cart AJAX code // The cart count will be updated via SignalR after the server processes the request }); }); });