I’m working on a custom WooCommerce product page where the user can select product variations (like size, color, etc.) and then add the product to the cart. Everything is functioning correctly, including the variation selection and the dynamic price update based on the selected variation.
However, I’ve encountered a problem. When a user selects a variation and clicks the ‘Add to Cart’ button, a fake alert appears, saying "Please select a variation," even though a valid variation has already been selected. After closing this fake alert, the product is successfully added to the cart, and a success message appears.
I want to prevent this fake alert from showing when the product is added to the cart successfully. How can I modify the event handling to ensure only the success alert is shown, and the fake alert doesn’t appear?
Any help or suggestions are appreciated!
global $product;
// Get the product's default price HTML
$default_price_html = $product->get_price_html();
// Get available variations
$available_variations = $product->get_available_variations();
$product_id = $product->get_id();
echo '<div class="custom-product-price" style="text-align:center;">';
echo '<p id="product-price-' . $product_id . '" style="font-size:18px;font-weight:bold;">Price: ' . $default_price_html . ' </p>';
echo '</div>';
echo '<div class="custom-product-variations" style="text-align:center;">';
$attributes = $product->get_variation_attributes();
foreach ($attributes as $attribute_name => $options) {
echo '<div class="variation-group">';
foreach ($options as $index => $option) {
$input_id = 'attribute_' . sanitize_title($attribute_name) . '_' . $product_id . '_' . $index;
echo '<input type="radio" id="' . $input_id . '" class="variation-option" name="attribute_' . sanitize_title($attribute_name) . '_' . $product_id . '" value="' . esc_attr($option) . '" data-attribute_name="' . sanitize_title($attribute_name) . '" data-product_id="' . $product_id . '">';
echo '<label for="' . $input_id . '">' . esc_html($option) . '</label>';
}
echo '</div>';
}
echo '</div>';
echo '<div class="custom-add-to-cart">';
echo '<button id="add-to-cart-button-' . $product_id . '" disabled>Add to Cart</button>';
echo '</div>';
echo '<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var productID = "' . $product_id . '";
var variationOptions = document.querySelectorAll(".variation-option[data-product_id=\'" + productID + "\']");
var priceElement = document.getElementById("product-price-" + productID);
var addToCartButton = document.getElementById("add-to-cart-button-" + productID);
var selectedVariationId = null;
var availableVariations=" . json_encode($available_variations, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ";
var defaultPriceHtml=" . json_encode($default_price_html) . ";
// Function to update the price display
function updatePrice(priceHtml) {
priceElement.innerHTML = "Price: " + priceHtml;
}
// Function to find and set the matching variation
function findMatchingVariation(selectedAttributes) {
return availableVariations.find(function (variation) {
return Object.keys(selectedAttributes).every(function (key) {
return variation.attributes[key] === selectedAttributes[key];
});
});
}
// Function to gather selected attributes
function getSelectedAttributes() {
var selectedAttributes = {};
variationOptions.forEach(function (opt) {
if (opt.checked) {
var attrName = "attribute_" + opt.getAttribute("data-attribute_name");
selectedAttributes[attrName] = opt.value;
}
});
return selectedAttributes;
}
// Event listener for option changes
variationOptions.forEach(function (option) {
option.addEventListener("change", function () {
var selectedAttributes = getSelectedAttributes();
// Find matching variation
var matchingVariation = findMatchingVariation(selectedAttributes);
// Update the price and enable the Add to Cart button if a matching variation is found
if (matchingVariation) {
var priceHtml = "<span class=\"woocommerce-Price-amount amount\"><bdi><span class=\"woocommerce-Price-currencySymbol\">$</span>" + matchingVariation.display_price.toFixed(2) + "</bdi></span>";
updatePrice(priceHtml);
selectedVariationId = matchingVariation.variation_id;
addToCartButton.disabled = false; // Enable the Add to Cart button
} else {
updatePrice(defaultPriceHtml);
selectedVariationId = null;
addToCartButton.disabled = true; // Disable the Add to Cart button
}
});
});
// Add to Cart button click event
addToCartButton.addEventListener("click", function (event) {
// Before proceeding, check if any variation is selected and valid
if (!selectedVariationId) {
// Stop the function from proceeding and show the appropriate alert
event.preventDefault();
alert("Please select a variation before adding to cart.");
return;
}
// If variation is selected, proceed with the add-to-cart functionality
var formData = new FormData();
formData.append("action", "woocommerce_add_to_cart");
formData.append("product_id", selectedVariationId); // Use the selected variation ID
formData.append("variation_id", selectedVariationId);
formData.append("quantity", 1);
// Include selected attributes in the form data
var selectedAttributes = getSelectedAttributes();
for (var key in selectedAttributes) {
if (selectedAttributes.hasOwnProperty(key)) {
formData.append(key, selectedAttributes[key]);
}
}
fetch("' . admin_url('admin-ajax.php') . '", {
method: "POST",
body: formData,
credentials: "same-origin"
})
.then(function (response) {
return response.json();
})
.then(function (data) {
if (data.error) {
alert("Error adding to cart: " + data.error);
} else {
alert("Product added to cart successfully!");
// Optionally, update the cart count or show a success message
var cartCountElement = document.querySelector(".cart-count");
if (cartCountElement) {
cartCountElement.textContent = data.cart_count;
}
}
})
.catch(function (error) {
alert("There was an error processing your request. Please try again.");
});
});
});
</script>'; ```
You need to sign in to view this answers
Leave feedback about this