If I'm announcing a coupon in my ad, I want it to be automatically applied to the cart when people click on the ad. I have created a workaround for this; add "?coupon=YOUR_COUPON" to any link to your website and the coupon will be automatically applied to the cart.
To accomplish this add this code to the global code section:
<script>
// Function to get query string parameters
function getQueryStringParam(param) {
var queryParams = new URLSearchParams(window.location.search);
return queryParams.get(param);
}
// Function to set a cookie
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
// Get the coupon code from the query string
var couponCode = getQueryStringParam('coupon');
// If there's a coupon code in the URL, set it as a cookie
if (couponCode) {
setCookie('coupon', couponCode, 7); // Set the coupon cookie for 7 days
}
</script>
And add this code to the cart page code section:
<script>
document.addEventListener('DOMContentLoaded', function () {
// Function to get cookie value by name
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
// Get the coupon code from the cookie
var couponCode = getCookie('coupon');
// If there's a coupon code in the cookie
if (couponCode) {
// Prepare data to be sent in the request
var data = new FormData();
data.append('couponCode', couponCode);
// Extract and append CSRF token if required
var csrfToken = document.querySelector('input[name="_token"]').value;
if (csrfToken) {
data.append('_token', csrfToken);
}
// Perform the AJAX request to apply the coupon
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://studyofmemes.com/checkout/code', true); // Replace with your actual endpoint
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// Handle successful coupon application
console.log('Coupon applied successfully:', couponCode);
} else {
// Handle errors
console.error('Error applying coupon:', couponCode);
}
}
};
// Set up request header for form submission
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Convert FormData to URL-encoded string
var urlEncodedData = new URLSearchParams(data).toString();
xhr.send(urlEncodedData);
}
});
</script>