FROM CACHE - en_header

Wait for onClick event to be finished (inserted by script tag) before redirecting to checkout page

abdullah_omar04
Excursionist
24 0 1

Hey everyone,

I am creating an app that deals with discounts. The idea is to generate a discount code based on a user's cart total price and dynamically generate discount code and apply it for them on checkout page.

For example, if a user has $200 worth of products, when he/she clicks on "Go to Checkout" button an onClick event triggers which is inserted via script tag and generates a discount code based on cart value and applies it to checkout page automatically.

But, before the whole process can be completed the store redirects to checkout page and the discount code does not get applied even though it gets generated successfully.

Is there any way to deal with this situation?
Like a way to redirect only after the onClick event has finished? or any other way? or any other approach?

Please help me resolve this.

Replies 12 (12)
Greg_Kujawa
Shopify Partner
1023 84 266

If this logic lives in client-side JavaScript, couldn't you do something along the lines of this?

$('.button').on( 'click', function(e){
    $.when( myOwnFunction(e) ).done(function() {
        alert('myOwnFunction is finished')
    });
});
abdullah_omar04
Excursionist
24 0 1

@Greg_Kujawa , I am sorry but your comment seems quite vague.

Can you please further elaborate what you are suggesting?

Greg_Kujawa
Shopify Partner
1023 84 266

Without your providing some code snippets, my response was about as specific as possible. There is a .done callback that's available. Which will only come into play when your own function has completed. In this case, it would be when your own function has whipped up whatever discount code and whatnot.

abdullah_omar04
Excursionist
24 0 1

@Greg_Kujawa , sorry I should have put my code snippet.

Here it is:

let cartButton = document.querySelector(".cart__submit");

if (cartButton) {
  cartButton.addEventListener(
    "click",
    (e) => {
      //fetch cart obj
      fetch(`/cart.js`)
        .then((res) => res.json())
        .then((cartObj) => {
          fetch(`${serverAddress}/api/createDiscountCode`, {
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(cartObj),
          })
            .then((res) => res.json())
            .then(({ dicountCode }) => {
              //make get req to send and apply the discount code on the checkout page
              fetch(
                `https://${shop}/discount/${dicountCode.discount_code.code}`
              ).catch((err) => console.log(err));
            })
            .catch((err) => console.log(err));
        })
        .catch((err) => console.log(err));
    }
  );
}

 

Can you please tell me where and how I should put my done callback here?

Greg_Kujawa
Shopify Partner
1023 84 266

Maybe try replacing

.then((cartObj)...

with this

.done((cartObj)...

 The .done part I believe waits until that callback has completed. At least for JQuery > v1.8 if I'm not mistaken. Worth a shot at least!

abdullah_omar04
Excursionist
24 0 1

Does not work unfortunately...

Any other ideas? 

Also, I need to avoid using jQuery since its not preinstalled in many themes these days

Greg_Kujawa
Shopify Partner
1023 84 266

I'm not sure what packages your project is using, but I revisited my code I have for a Shopify POS Embedded App SDK project. It basically creates a non-stock item on the fly and adds that new item to the user's cart. I too ran into similar overrun, problems where the item didn't exist yet to add to the cart. So the cart is empty. I inserted a wait(2000) line into my code to wait for the new item to be created. Not the most elegant solution, since that is synchronously blocking the UI, but it worked for a crude implementation for my test case. Non-production though...

abdullah_omar04
Excursionist
24 0 1

I just tried putting a setTimeout() in my code, but still redirects.

I don't know how you did it but mine just won't work

Greg_Kujawa
Shopify Partner
1023 84 266

My code uses the wait() function to wait 2 seconds before proceeding through the remainder of the window.onload() function. Like this. So this results in a noticeable UI delay while the vendors are fetched, before displaying them in the form to the user. Not elegant as I mentioned, and not production ready. But the 2 seconds allowed adequate time for the external API call to succeed. I have other projects that use jQuery where using .done() was more effective and not as clunky. 

window.onload = function() {
        $('header').remove();
        $('footer').remove();        
      	getVendors();
        wait(2000);
      	listVendors();
      	};     

 

abdullah_omar04
Excursionist
24 0 1

I would like to try this out but how or where exactly are you getting this "wait" function from?

Greg_Kujawa
Shopify Partner
1023 84 266

It was just a Promise wrapper around the same setTimeout function you tried. Sorry, just dug into that now...

abdullah_omar04
Excursionist
24 0 1

I don't understand why nothing is working.

I just need to delay the other function that runs by just a few seconds somehow