6

As a new Magento student was thinking is it possible to do something like this ...

    var url = product['image'];
    var image = '<?=Mage::helper("imageprocessor")
            ->getImgProcessor( >> js variable here << ,10,20,NULL)?>';

is it possible at all ? or the only way is ajax request? I tried "->getImgProcessor('+variablename+')" and similar things but ... it does not work this way.

  • Where are you using this code? In phtml file? – Priyank Dec 20 '17 at 10:19
5

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.
6

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>
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.