Problems in parsing variables from php to javascript -
scenario: tracking events(add cart, search terms, product views, etc) test e-commerce website(opencart), javascript function written in footer page , these functions called @ button triggers or page loads.
problem: while tracking product view event following code added product page, function captureproductview()
called footer, , parameters clientid, fname, lname
retrieved 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 values php variables $product['product_id']
, $product['name']
, $product['price']
cannot parsed script tag, leaving notice:
notice : undefined variable: product in /home/path.../product.tpl on line 29"
for 3 variables
i tried assigning these values javascript variables, did not work.
var p_id = "<?php echo $product['product_id']; ?>"; var p_name = "<?php echo $product['name']; ?>";
is there way can parse php variables script tag, can passed parameters function?
you error because associative array $product
not defined in php script renders page.
your first option edit script $product['product_id']
, $product['name']
, $product['price']
defined , assigned proper values.
note first snippet of code have syntax error you're mis-using single quote. have use both single , double quotes:
captureproductview('<?php echo $product["product_id"]; ?>', '<?php echo $product["name"]; ?>', '<?php echo $product["price"]; ?>', clientid, fname, lname);
you have second option parsing javascript values rendered page.
captureproductview( $('input[name=product_id]').val(), $('h1').text().trim(), $('.price').text().trim(), clientid, fname, lname);
this worked on layout tried may need minor changes on different layout target appropriate page elements fetch values from.
note used jquery retrieve value page elements.
the value price string "price: $24"
, depending on needs may require further basic string manipulation extract price value (24
in example).
for reference tried above on page:
http://themes.webiz.mu/opencart/apparel/index.php?route=product/product&product_id=69
however discourage approach because layout changes function may break.
all above 2 options assume captureproductview
sending data server ajax request , clientid
, fname
, lname
defined in javascript code.
Comments
Post a Comment