Personalized checkout and custom promotions with Shopify Scripts
I want to trigger a custom script about GTM code when the user login successfully. But the page will be redirected to other pages when the user clicks the login button. Does anyone know how to fix it?
{% if shop.checkout.guest_login %}
<div class="text-center">
<hr class="hr--invisible">
<h2>{{ 'customer.login.guest_title' | t }}</h2>
{% form 'guest_login' %}
{% if form.posted_successfully? %}
<span data-success class="hide"></span>
<script>
console.log('Login successfully ') //doesn't work
</script>
{% endif %}
<input type="submit" class="btn btn--primary btn--form" value="{{ 'customer.login.guest_continue' | t }}">
{% endform %}
</div>
{% endif %}
{% if form.posted_successfully? %} will not work. I tried to assign form.posted_successfully? to a variable and grab its value couldn't make it work but you can try another alternative which is to pass a parameter to the success URL and set a trigger in GTM for all pages that checks for that paramter
Add this to your Login Form
<input type="hidden" name="checkout_url" value="/account?login_success=true">
Add this to your Body tag
<body data-customer-id="{{customer.id}}">
On GTM you could do something like this
or in your code you could do something like this:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const loginSuccess = urlParams.get('login_success');
const customer = document.querySelector('[data-customer-id]');
const customerId = customer.getAttribute('data-customer-id');
if (loginSuccess) {
dataLayer.push({
event: 'login',
user_id: customerId,
});
console.log('login');
// Remove params from URL to avoid multiple events to fire.
window.history.pushState({}, null, window.location.href.split('?')[0]);
}
Let me know if it works or if someone made the {% if form.posted_successfully? %} works
Starting a B2B store is a big undertaking that requires careful planning and execution. W...
By JasonH Sep 23, 2024By investing 30 minutes of your time, you can unlock the potential for increased sales,...
By Jacqui Sep 11, 2024We appreciate the diverse ways you participate in and engage with the Shopify Communi...
By JasonH Sep 9, 2024