How to mix js with php in phtml?

If you are using this code in some template file say for example

test.phtml

<?php $product = Mage::getModel('catalog/product')->load(1); ?>
<script>
     // To get Any data in your javascript variable
     var sku = '<?php echo $product->getSku() ?>';
     var image = '<?php echo Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(100); ?>';
</script>

If I understood well, you have to add your phtml in head then you can get your helper in your js

app/design/frontend/{your package}/{your module}/layout/local.xml

<reference name="head">
    <block type="page/html" name="my.custom.block" template="page/html/mycustomblock.phtml"/>
    <action method="addItem"><type>js</type><name>myjs.js</name></action>
</reference>

app/design/frontend/{your package}/{your module}/template/page/html/mycustomblock.phtml

<script type="text/javascript">
    var image = <?php echo Mage::helper('yourhelper')->yourMethod();?>;
</script>

And in your js you can get your image helper var image

myjs.js

alert(image); //for exemple

So if I understand it correctly, you want to use the value of a Javascript variable in a PHP function.

Unfortunately, that won't work. All javascript happens on the client side, i.e. in the browser. PHP is a server-side language, it all happens on the server.

Generally, what happens in the sequence of requests is:

  • The client asks the server for a page;
  • The server receives the request and looks for the PHP source to use;
  • The server processes ALL the PHP code to valid HTML code that the browser can use.
  • The server sends the finished HTML code to the client;
  • The client's browser reads all of the HTML and interprets it, including inline javascript.
  • The client side javascript gets executed.

As you can see, the server side code doesn't know about the Javascript or the variables defined in javascript, and the browser doesn't know anything about the PHP used to generate the page. If you have a Javascript object you need to use in PHP, there are really only 2 options:

  1. You do the object processing server-side completely, so instead of trying to find the image url in the javascript, you store and read it on the server side;
  2. You use an AJAX request to get the image url from the server to the client.