-1

Background:

I have a popup that request emails from users. Should they complete the email submit, I would like to apply a coupon code automatically should they subsequently make a purchase at checkout.

For coupon codes to be applied, all users have to do is access a link with /?coupon_code=xxxx at the end of the url.

This code was obtained here: GET a coupon code via URL and apply it in WooCommerce Checkout page

Problem:

How do I add the /?coupon_code=xxxx when a user closes the popup?

What I have tried:

I have tried to use the solution offered here (Change URL without refresh the page). This is what I inserted.

history.pushState(null, '', '/?coupon_code=xxxx');

While this works in changing the url, I find that the coupon code is not applied at checkout. However, if I manually entered the full url and refreshed the page eg. www.test.com/?coupon_code=xxxx, the coupon code will be applied at checkout.

Thank you.

xojijog684
  • 150
  • 7

1 Answers1

0

Would making an AJAX/fetch request work in this scenario? I’m not entirely sure I understand the question, but perhaps you could try:


let onClose = async () => {
    let response = await fetch(‘/?coupon_code=xxxx’);
    let data = await response.json();
    return data; //returns the result of your request to the coupon code URL
}

hope this helps!

Edit: to explain why this works

When you change the history state, all that is being affected is the browsers local state. To apply the coupon code, you actually need to make an http request to the URL you’ve provided, which is what the fetch API does. It’s asynchronous, which is why we’re using async/await. It could also be done by chaining .then(), if you preferred.

A. Eglin
  • 11
  • 4
  • Thank you. May I know if there is a way to achieve what I want using javascript only? The reason for that is that I don't know enough about programming to implement your solution. – xojijog684 Feb 26 '20 at 15:41