i have a php e-commerce website When i add product to cart from category A then move to category B product that already added from category A can not increase or decrease from cart side until i moved back to category A.in same category window it works fine.when i click on category button in console this error show products.php?category_id=4:1607 Uncaught ReferenceError: toggleSidebar is not defined
at HTMLAnchorElement.onclick (products.php?category_id=4:1607:47).
i already review session data its fine between three files.this is script
<script>
// Function to toggle cart sidebar
function toggleCart() {
$('.cart-sidebar').toggleClass('active');
$('.overlay').toggleClass('active');
if ($('.cart-sidebar').hasClass('active')) {
loadCartSidebar();
}
}
// Function to load cart sidebar content
function loadCartSidebar() {
$.ajax({
url: 'cart_dropdown.php',
type: 'GET',
success: function(response) {
$('#cart-sidebar-content').html(response);
}
});
}
// Function to update cart
function updateCart(productId, action) {
const quantityType = $(`#quantity-type-${productId}`).val();
const quantity = $(`#quantity-${productId}`).val();
$.ajax({
url: 'update_cart.php',
type: 'POST',
data: {
product_id: productId,
action: action,
quantity_type: quantityType,
quantity: quantity
},
success: function(response) {
let data = JSON.parse(response);
if (data.error) {
alert(data.error);
} else {
$('#cart-count').text(data.cartCount);
$('#cart-total').text('$' + data.cartTotal.toFixed(2));
loadCartSidebar();
// Enable/Disable the Order Submit button based on cart count
if (data.cartCount > 0) {
$('#order-submit').prop('disabled', false);
} else {
$('#order-submit').prop('disabled', true);
}
// Show/hide the minus button based on the product's quantity in the cart
if (data.cartCount > 0) {
$(`#minus-${productId}`).show(); // Show minus button
} else {
$(`#minus-${productId}`).hide(); // Hide minus button
}
// Show discount tag if applicable
if (data.discountApplied) {
const totalSaved = data.totalSaved.toFixed(2);
$(`#discount-tag-${data.productId}`).show().find(`#discount-amount-${data.productId}`).text(totalSaved);
} else {
$(`#discount-tag-${data.productId}`).hide(); // Hide the tag if quantity is below packets_per_pallet
}
// Show discount popup if applicable
if (data.discountApplied) {
const totalSaved = data.totalSaved.toFixed(2);
const newPrice = data.newPrice.toFixed(2);
const productName = $(`#product-${data.productId} h4`).text(); // Get product name
$('#discount-popup').html(`🎉 You saved $${totalSaved} on ${productName}! Now you get this price: $${newPrice} 🎉`).fadeIn().delay(3000).fadeOut();
}
}
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
}
});
}
// Function to handle order submission
$(document).ready(function() {
$('#order-submit').click(function() {
if ($(this).prop('disabled')) {
return; // Do nothing if the button is disabled
}
// Handle the order submission
$.ajax({
url: 'submit_order.php',
type: 'POST',
success: function(response) {
alert('Order submitted successfully!');
// Optionally, clear the cart or redirect the user
window.location.href = 'thank_you.php';
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
alert('There was an error submitting your order. Please try again.');
}
});
});
// Toggle CategorÃÂa Sidebar
$('.bottom-nav a').on('click', function(e) {
if ($(this).attr('href') === '#') {
e.preventDefault();
$('.sidebar').toggleClass('active');
$('.overlay').toggleClass('active');
}
});
// Close sidebar and cart sidebar when clicking outside
$(document).on('click', function(event) {
if (!$(event.target).closest('.sidebar').length && !$(event.target).closest('.bottom-nav a').length) {
$('.sidebar').removeClass('active');
$('.overlay').removeClass('active');
}
if (!$(event.target).closest('.cart-button').length && !$(event.target).closest('.cart-sidebar').length) {
$('.cart-sidebar').removeClass('active');
$('.overlay').removeClass('active');
}
});
// Back Arrow in Cart Sidebar (Mobile)
$('.cart-sidebar').on('click', '.back-arrow', function() {
toggleCart();
});
// Live Search Functionality
$('.search-bar').on('input', function() {
const query = $(this).val();
if (query.length > 2) { // Only search if query has at least 3 characters
$.ajax({
url: 'search_products.php',
type: 'GET',
data: { query: query },
success: function(response) {
$('.search-results').html(response).show();
}
});
} else {
$('.search-results').hide();
}
});
// Close search results when clicking outside
$(document).click(function(event) {
if (!$(event.target).closest('.search-container').length) {
$('.search-results').hide();
}
});
// Handle click on search result item
$(document).on('click', '.search-results .product-item', function() {
const productId = $(this).data('product-id');
// Hide search results
$('.search-results').hide();
// Scroll to the product card and highlight it
const productCard = $(`#product-${productId}`);
if (productCard.length) {
$('html, body').animate({
scrollTop: productCard.offset().top - 100 // Adjust offset for better visibility
}, 500);
productCard.css('border', '2px solid #28a745'); // Highlight the product
setTimeout(() => {
productCard.css('border', '1px solid #ddd'); // Remove highlight after 2 seconds
}, 2000);
}
});
// Handle subcategory filter change
$('.subcategory-filter input[type="checkbox"]').change(function() {
const selectedSubcategories = [];
$('.subcategory-filter input[type="checkbox"]:checked').each(function() {
selectedSubcategories.push($(this).val());
});
const categoryId = <?= $categoryId ? $categoryId : 'null' ?>;
const url = new URL(window.location.href);
// Update or remove the 'subcategories' parameter
if (selectedSubcategories.length > 0) {
url.searchParams.set('subcategories', selectedSubcategories.join(','));
} else {
url.searchParams.delete('subcategories');
}
// Update or remove the 'category_id' parameter
if (categoryId) {
url.searchParams.set('category_id', categoryId);
} else {
url.searchParams.delete('category_id');
}
// Reload the page with the updated URL
window.location.href = url.toString();
});
// Function to scroll subcategories
function scrollSubcategories(direction) {
const scrollContainer = document.querySelector('.subcategory-filter-scroll');
const scrollAmount = 200; // Adjust scroll amount as needed
if (direction === 'left') {
scrollContainer.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
} else if (direction === 'right') {
scrollContainer.scrollBy({ left: scrollAmount, behavior: 'smooth' });
}
}
// Function to check if scrolling is needed and show/hide arrows
function checkScroll() {
const scrollContainer = document.querySelector('.subcategory-filter-scroll');
const leftArrow = document.querySelector('.subcategory-filter-arrow.left-arrow');
const rightArrow = document.querySelector('.subcategory-filter-arrow.right-arrow');
if (scrollContainer.scrollLeft > 0) {
leftArrow.style.display = 'block';
} else {
leftArrow.style.display = 'none';
}
if (scrollContainer.scrollLeft < (scrollContainer.scrollWidth - scrollContainer.clientWidth)) {
rightArrow.style.display = 'block';
} else {
rightArrow.style.display = 'none';
}
}
// Attach event listener for scroll
document.querySelector('.subcategory-filter-scroll').addEventListener('scroll', checkScroll);
// Initial check on page load
window.addEventListener('load', checkScroll);
});
// Function to handle WhatsApp button click
function openWhatsApp() {
alert("WhatsApp functionality is disabled for now.");
}
// Function to show location popup
function showLocation() {
document.getElementById('location-popup').style.display = 'block';
}
// Function to close location popup
function closeLocationPopup() {
document.getElementById('location-popup').style.display = 'none';
}
// Function to get directions
function getDirections() {
const address = encodeURIComponent('Carrer de l'Almirall Oquendo, 153, 08020 Sant Adrià de Besòs, Barcelona');
window.open(`https://www.google.com/maps/dir/?api=1&destination=${address}`, '_blank');
}
// Function to scroll to top
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
</script>