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

abdullah_omar04
Tourist
24 0 0

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.

0 Likes
Greg_Kujawa
Shopify Partner
951 80 203

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')
    });
});
0 Likes
abdullah_omar04
Tourist
24 0 0

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

Can you please further elaborate what you are suggesting?

0 Likes
Greg_Kujawa
Shopify Partner
951 80 203

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.

0 Likes
abdullah_omar04
Tourist
24 0 0

@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?

0 Likes
Greg_Kujawa
Shopify Partner
951 80 203

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!

0 Likes
abdullah_omar04
Tourist
24 0 0

Does not work unfortunately...

Any other ideas? 

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

0 Likes
Greg_Kujawa
Shopify Partner
951 80 203

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...

0 Likes
abdullah_omar04
Tourist
24 0 0

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

0 Likes
Greg_Kujawa
Shopify Partner
951 80 203

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();
      	};     

 

0 Likes