Scenario: For tracking events(Add to cart, Search terms, Product views, etc) from a test e-commerce website(Opencart), JavaScript function is written in the footer page and these functions are called at button triggers or page loads.
Problem: While tracking product view event following code is added to Product page, function captureProductView()
is called from footer, and parameters clientid, fname, lname
are retrieved from getClientDetails();
<script>
window.onload=function(){
getClientDetails();
captureProductView('<?php echo $product['product_id']; ?>',
'<?php echo $product['name']; ?>', '<?php echo $product['price']; ?>',
clientid, fname, lname);
};
</script>
But the values from php variables $product['product_id']
, $product['name']
, $product['price']
cannot be parsed to the script tag, leaving Notice:
Notice : Undefined variable: product in /home/path.../product.tpl on line 29"
for all those three variables
I tried assigning these values to javaScript variables, which also did not work.
var p_id = "<?php echo $product['product_id']; ?>";
var p_name = "<?php echo $product['name']; ?>";
Is there a way where I can parse the php variables to the script tag, so that they can be passed as parameters to the function?
You get an error because the associative array $product
is not defined in the PHP script that renders the page.
Your first option is to edit the script so that $product['product_id']
, $product['name']
, $product['price']
are defined and assigned with the proper values.
Note that your first snippet of code have a syntax error as you're mis-using the single quote. You have to use both single and double quotes:
captureProductView('<?php echo $product["product_id"]; ?>',
'<?php echo $product["name"]; ?>',
'<?php echo $product["price"]; ?>',
clientid, fname, lname);
You have a second option that is parsing with JavaScript the values from the rendered page.
captureProductView( $('input[name=product_id]').val(),
$('h1').text().trim(),
$('.price').text().trim(),
clientid, fname, lname);
This worked on a layout I tried but may need minor changes on a different layout to target the appropriate page elements to fetch the values from.
Note I used jQuery to retrieve the value from the page elements.
The value for price is a string like "Price: $24"
and depending on your needs may require further basic string manipulation to extract only the price value (24
in the example).
For reference I tried the above on this page:
http://themes.webiz.mu/opencart/apparel/index.php?route=product/product&product_id=69
However I strongly discourage this approach because as the layout changes the function may break.
All the above two options assume that captureProductView
is properly sending the data to the server with an AJAX request and clientid
, fname
, lname
are defined in the JavaScript code.