请求指导实现无页面刷新添加商品至购物车(JavaScript/Ajax新手求助)
Hey there! Let's break down why your no-refresh cart add isn't working, and fix it step by step. I see you're already on the right track with AJAX, but a few tweaks will get this working smoothly.
First, Identify the Core Issue
Your current code includes location.reload(); in the AJAX success callback—this is what's forcing the page to refresh. Removing that is the first step, but we need to make sure the rest of the flow works properly when we do.
Step 1: Remove the Page Refresh
Delete this line from your success callback:
location.reload();
Step 2: Ensure Default Actions Are Blocked
If your addToCart function is triggered by a link (<a>) or form submit button, you need to prevent the browser's default behavior (like navigating away or submitting the form normally). Add this to your click event handler:
// Example if you're binding to a button click $('.add-to-cart-button').click(function(e) { e.preventDefault(); // Stop the browser from reloading/navigating const productId = $(this).data('id'); // Get product ID from button data attribute addToCart(productId); });
Step 3: Add Error Handling to Debug Issues
Right now, you don't have any error handling for the AJAX request. If the request fails (e.g., invalid CSRF token, backend error), you won't know about it. Add an error callback to diagnose problems:
function addToCart(id) { if(checkAddToCartValidity()) { $('#addToCart').modal(); $('.c-preloader').show(); $.ajax({ type:"POST", url: '{{ route('cart.addToCart') }}', data: { "_token": "{{ csrf_token() }}", "id": id, "quantity": 1 }, success: function(data){ $('#addToCart-modal-body').html(null); $('.c-preloader').hide(); $('#modal-size').removeClass('modal-lg'); updateNavCart(); // Make sure this function updates your cart UI correctly $('#cart_items_sidenav').text(parseInt($('#cart_items_sidenav').text()) + 1); // Use text() instead of html() for numbers $('.add_to_card_sidebar').addClass('open'); // Removed location.reload() here console.log('Item added successfully!', data); // Debug log }, error: function(xhr, status, error) { $('.c-preloader').hide(); // Hide loader even if request fails console.error('Cart add failed:', error); console.log('Server response:', xhr.responseText); // Check backend errors AIZ.plugins.notify('danger', 'Failed to add item to cart. Please try again.'); } }); } else{ AIZ.plugins.notify('warning', 'Please choose all the options'); } }
Step 4: Verify Key Functions and Backend
- Check
updateNavCart(): This function should refresh your navigation cart's content (e.g., item list, total price). If it's not implemented correctly, the cart won't update visually even if the item is added. Make sure it fetches the latest cart data from the backend or updates the DOM directly. - Validate Backend Route: Ensure your
cart.addToCartroute's controller method correctly handles the POST request:- It should accept
idandquantityparameters - It should add the item to the user's cart
- It should return a successful response (e.g.,
return response()->json(['success' => true, 'cartCount' => $cartCount]);)
- It should accept
Final Notes
- Use
text()instead ofhtml()when updating the cart item count (like$('#cart_items_sidenav').text(...)) to avoid potential HTML injection issues. - Check your browser's developer tools (Network tab) to see if the AJAX request is going through, and what the server is returning.
内容的提问来源于stack exchange,提问作者Venkatesh K

