Magento Base URL – How to Get Base URL in JavaScript

layoutmagento-1.7magento-1.8magento-1.9template

<reference name="head">
<block type="fabric_tool/tool" name="js" template="fabric/tool/global.phtml"/>

<action method="addItem"><type>skin_js</type><file>js/fabric/tool/men_default.js</file></action>
</reference>

in global.phtml file, I have code like

<script>
     var BASE_URL='<?php echo Mage::getBaseUrl();?>';
</script>

in men_default.js, I have taken BASE_URL. But When application is loaded, JS is appended before global.phtml is appended. so that, I can not access BASE_URL variable in men_default.js. So What do I have to do? Is there any solution?

Best Answer

This is not possible. Because..

child blocks which are included inside head block will get only rendered after rendering/including js and css which are added in head block, irrespective of the point of inclusion in the layout update xml.

Proof : head block stands for Mage_Page_Block_Html_Head and by default it uses page/html/head.phtml file. Inside that file, you can see this

<?php echo $this->getCssJsHtml() ?>
<?php echo $this->getChildHtml() ?>

From the above code, it is obvious that, blocks included in head section will get rendered "later".

So you can probably go with below method. It may work in your case.

You need to add menu_default.js inside the phtml file itself.

That is your layout update xml should only contain the phtml file.

<reference name="head">
    <block type="fabric_tool/tool" name="js" template="fabric/tool/global.phtml"/>
</reference>

Here you need to make sure the above js block type is actually valid and does define inside magento block section.

Next update your global.phtml file with this content.

<script>
     var BASE_URL='<?php echo Mage::getBaseUrl();?>';
</script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/fabric/tool/men_default.js');?>"></script>

This way javascript variable BASE_URL is now defined before menu_default.js and hence you can get the value inside that file.

Related Topic