Tracking Conversion Value on GTM without Data Layer on Ecommerce - javascript

how are you doing? Hope you're fine.
My name is Thiago. I'm a brazilian enterpreneur that runs a Marketing Agency.
It's been a very long while since I'm in need of help with a very specific matter.
I'll try to explain it here the clearest and easiest as possible.
I'd like to ask sorry for any bad english in advanced. =D
So, the thing is, conversion is a big game changing, whatever it's on Facebook or Google.
Setting up conversions it self isn't that hard, when you have an ecommerce platform that comes with a data layer already setup.
Most of my clients doesn't have an ecommerce with a Data Layer.
I was following the Measure School youtube tutorial to install Active Campaign Tracking, and by doing this I add a template in my Google Tag Manager that almost soved the problem, but the code is note quite working.
And that's where I need help. =D (sorry for the long story kkk)
The Custom Variable "Purchase Function" code is this:
function() {
var price = str.split("Adicionar R$ ", "{{Click Text}}",[1])
return price
}
It's returning unedefined.
I'll add some prints showing the whole process with the most details as possible.
0 - Adding Product to Cart
1 - Product Price in Button Click Text
2 - Purchase Price Not Working
3 - GTM Price Function
I really need help making this Custom Variable "Purchase Price" works.
Thanks a lot.

You are using the split function wrong (for starters, you apply it to a variable str which is undefined. Also, wrong number of parameters and wrong parameters).
Look at the documentation for split here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
Your function should look something like this:
function() {
// splits Click Text by whitespace an returns an array
var parts = {{Click Text}}.split(" ");
// pop removes the last part from the array and returns it
// numerical index might not work if there is more than one whitespace in the click text
price = parts.pop();
return price;
}

Related

What parameters does shopify's 'OptionSelectors' actually need?

I'm running circles here and I'm out of idea's/google searches. There are so many different examples but all seem to do something different or don't work. According to shopify, this is the only documentation I can find around using their API: https://shopify.dev/tutorials/customize-theme-use-products-with-multiple-options
A ghost object I see, no matter, more and more searches I still can't figure out what this parameter is supposed to be.
I've attempted passing a json object of products as I've seen it done in various other theme examples:
var product = document.querySelector("[data-product-json]").innerHTML,
product = JSON.parse(product || '{}');
console.log(product);
jQuery(function($) {
new Shopify.OptionSelectors('productSelect-' + product.id, {
product: product,
onVariantSelected: selectCallback
});
});
The console log gives the correct object and json, nice.
OptionSelectors errors out:
Uncaught TypeError: Cannot read property 'parentNode' of null
at Shopify.OptionSelectors.replaceSelector (option_selection-fe6b72c2bbdd3369ac0bfefe8648e3c889efca213baefd4cfb0dd9363563831f.js:1)
at new Shopify.OptionSelectors (option_selection-fe6b72c2bbdd3369ac0bfefe8648e3c889efca213baefd4cfb0dd9363563831f.js:1)
I've given it just the product.id and various other things.
I'm going to out on a whim here and say the Shopify documentation is detailed, yes, but it is not developer-friendly in my opinion. They give you so much information but never what you really need.
Shopify products have a pretty simple, but weird in a way organization. First off, a product has an array of up to three things known as options. Can be empty. But as soon as you assign an option to a variant, this gets filled in. So you have your three options. Eg: Name, Size, Color, Material and on and on.
A variant has the actual value of the options. So if you provided option 1 as Size, a variant would have option1 equal to a size value, like "large". Repeat and layer in the other options, till a variant perhaps has 3. Now, reverse that process to simply get an ID so you can update a price, or some other logic!
So in this way, up to 100 variants can have 3 distinguishing options, all different. Going way back to Shopify early days, they produced some code that ended up lasting about ten years, and your snippet of OptionSelectors is an offshoot of that mess.
The challenge is to do what that old code did, but for your theme purposes. Many libraries and themes have done just that. But be aware they also used code that is not exactly easy to fork and use for your own purposes either.
So if you find hacking this old Shopify code to be a mind-numbing experience, you might do better to just rebuild Humpty Dumpty yourself so you completely understand it. You do not need to use their code. It is also super confusing because when Theme authors spawn yet another version of this code, they often thought they'd be clever and rename a few things or target a few different things, and thus establish themselves as "unique, more skilled" players, but in fact, this just adds to your misery, as they did not accomplish much.
So yes, all the best to you in your endeavors. Taking apart that code and learning it is a rite of passage most theme authors undergo. Yes, they swear. Yes it reveals some WTF moments. But in the end, you'll control your variants, and achieve glory.
I strongly recommend David Lazar's answer and that you take some time to build your own function(s) that can do the job of breaking down a product's options and associated values into customer-friendly options and then translating those selections into a single valid variant ID. It's not too hard and sometimes kinda fun.
However, if you just want to get the OptionSelectors code working:
var product = document.querySelector("[data-product-json]").innerHTML,
product = JSON.parse(product || '{}');
console.log(product);
jQuery(function($) {
new Shopify.OptionSelectors('productSelect-' + product.id, {
product: product,
onVariantSelected: selectCallback
});
});
The first parameter that goes into the function is the ID of the (usually hidden) element inside your form that will store the value of the ID of the selected variant.
The error you are getting from the OptionSelectors code:
Uncaught TypeError: Cannot read property 'parentNode' of null
is most often thrown when the code doesn't find that element.
So to fix your problem, in your product form you should just need to find (or create) an input field with name="id" and make sure that element has an ID that matches what you're using.
For example:
<input type="hidden" id="productSelect-{{ product.id }}" name="id" value="{{ product.selected_or_first_available_variant.id }}" />
(Alternatively, find your input with name="id" and take the ID attribute from that field and use it in your call to OptionSelectors)
The problem you will encounter is that different themes change what they pass. You are better off creating your own event handler to get the variant id and lookup the variant details that your code requires.
See Shopify trigger function on variant selection but don't override existing functionality for some tips on how to set that up.

Check Shopify variant stock from variant ID in JavaScript with JSON

I've created a JQuery script that has multiple selector forms to narrow down a complicated multi-sku product in Shopify.
By the time the customer has selected everything, the shopify variant IDs are returned as variables via an array (not getting data directly from Shopify).
e.g.
var idone = "15065378226219"
var idtwo = "13367973249067"
Now I want to use these values to get the variant inventory quantity. I've tried this code
function getValues(callback) {
$.getJSON("/admin/variants/15065378226219.json",function(result){
callback(result); // this should be the return value
});
}
getValues(function(values) {
alert(values);
});
But the alert doesn't do anything, so I don't think anything's happening. My goal is to get the variant inventories for both IDs so I can validate in JS whether or not the product is available (both IDs have inventory greater than 0).
Any guidance would be appreciated!
Thanks
When you access your complex product in Liquid, there is a filter that shows the product off as JSON. Amazingly, this filter is 'json'. So try this Liquid:
var fizzborked = {{ product | json }};
You can inspect that in a comment, or however you wish. Look for your variants. Note the inventory quantity being there. Use that to build your logic. You can no longer make callbacks to Shopify for inventory amounts. 10 years ago people were complaining about having their inventory levels scraped, so Shopify cut that off.
As far as more sophisticated approaches go, you could always use a private App to support a Proxy call, allowing you to make secure Ajax calls to cull whatever data you need to support your use-case. Win Win!

AJAX update category - category - product on Homepage

I need to create, I think, something quite complicated and was wondering if some people could help me out with ideas/tutorials/examples.
The thing is our client wants a step-by-step-system on the homepage where the customer can already choose between different categories and then view the asociated products.
Yes I know about Layered Navigation and AJAX stuff by Amasty etc but I don’t think thats what I need in this situation. Let me explain step by step.
First off, it’s a phone repair shop.
The section consists of 4 columns, each column should update according to what you have choosen before that one.
The first column consists of the main categories (brands of phones) if you choose lets say HTC then the second column should show the subcategories of HTC. Then after youve choosen a type of phone the third column should update with the possible repairs (the products). Then after choosing one of the repairs(products) the fourth column should update with the price etc and show you the ‘Proceed to checkout’ button.
All these updates should occur using AJAX obviously because constantly reloading the page is an annoyance.
Im quite familiar with Magento’s structure, I think I know enough to create my own module and my knowledge of PHP and jQuery/Javascript should be sufficient. But I have no idea where to start and how complicated this is. Because we have a set development time Im not sure I can do this within the limits of agreed time.
Hope anyone could share some insights and ideas!
The Netherlands (hence the possible grammar errors :P)
You should probably just make an ajax request function for every part of the webpage you want to update. You can send the response text to a callback function which will build up the column
function loadFilter(variable1,variable2,option,div){
$.post("../filtros.php",
data:{ variable1:var1, variable2:var2, option:option},
function(data){
$("#"+ div+"").html(data);
}
);
}
$("#var1").click(function(){
loadFilter($(this).val(),"","option1","div1");
});
$("#var2").click(function(){
loadFilter($("#var1").val(),$(this).val(),"option2","div2");
});
And php(../filtros.php)
$option=$_REQUEST["option"];
if($option=="var1"){
$query = "select * from yourtable where var1 =". $_REQUEST["var1"];
}
if($option=="var2"){
$query = "select * from yourtable where var1 =". $_REQUEST["var1"].
"and var2 = ".$_REQUEST["var2"];
}
foreach(query as q){
echo q;
}
when click on #var1 load its data(var2)
and click on #var2 load its data
What you're looking for is called a "Faceted Search". Searching the web for that exact phrase should yield some pretty good results. I did that and came across this GitHub project. It has a nice example page and you should be able to read through it's source code for some tips. Some other people have asked similar questions, so this question might be flagged as a duplicate. Take a look at other StackOverflow questions, this one might be helpful: Javascript Faceted Search Client (Framework)
Good luck.

How to append string to the url and then make url show the string?

Javascript = looked through Google and Stack Overflow -I am still lost as I am still new in programming and everything else. I have some questions that I need to know
so far, I have this below:
var getUrladdress = window.location.href; //get current url address
var sortbydiscount = "?sortby";
var discount = ["20","30","50","70"];
What I wanted to know how to do is:
append string from discount array (I have tried to use append() but it doesn't work :(
then compare the discount array against percentDiscount (still being worked on in other question)
sort the items (final one) to display all items under 20%, 30% etc group.
Could you please give me insight/guide me on how to append string from discount array and then have the url show that "http://www.xxx.com?sortby30" in live address bar?
Then could it be possible to compare array against percentDiscount?
Many thank yous in advance.
EDITED:: #3 - I wanted to have sale items categorized in different discount group: i.e. if 20%, then all items which are on sale for 20% should be only displayed on the page.
You really should get a good book on JavaScript and learn from that if you are so unsure about core language features. That said:
You are confusing appending an HTML element using jQuery (just one of the web application libraries or "frameworks" available for JavaScript) with appending one string to another (concatenating strings). The plus operator can be used to concatenate strings:
getUrladdress = getUrladdress + sortbydiscount;
To check to see if a particular item is in an array, you can use the .indexOf method of the array. Because the method was added only in ES5 (the latest version of the ECMAScript/JavaScript specification), the documentation I have linked to includes contains some compatibility code to use to get this to work on Internet Explorer.
if(discount.indexOf(percentdiscount) != -1) {
// found
} else {
// not found
}
I'm not sure what you mean by that one; perhaps you can clarify exactly what you are trying to do? Show a list of items under each discount percentage on the web page?

Need help with an AJAX workflow

Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \

Categories