What is the best way to determine a Magento store's base url from inside javascript?
I'm working on a reusable extension that needs to know the store's base url in javascript in order to do some Ajax calls. One would think a property like
Mage.baseUrl
would be available, but I can't find it.
An alternative would be to add the base url as a bit of inline javascript, but I can't find any information on how to add inline javascript programmatically (only external js files), without altering the template.
By default this information isn't (reliably, stably) exposed via Javascript. You're going to need to expose it yourself via a custom block added to the layout. The easiest way to do this will be
Adding the block via your theme's local.xml
file
Adding a template to your theme for the above block
To add the block to the layout via your local.xml
file, something like this should suffice
<default>
<reference name="root">
<block name="my_custom_js_block">
<action method="setTemplate">
<template>my_custom_js_block/extra-js.phtml</template>
</action>
</block>
</reference>
</default>
Then add the following folder and file to your theme
app/design/frontend/default/your_theme/template/my_custom_js_block/
app/design/frontend/default/your_theme/template/my_custom_js_block/extra-js.phtml
At this point you have a phtml
template file that will be rendered on every page. You can add whatever javascript variables you want. I'm fond of a pattern something like
#File: app/design/frontend/default/your_theme/template/my_custom_js_block/extra-js.phtml
<?php
$h = Mage::helper('core');
$info = new stdClass();
$info->base_dir = Mage::getBaseDir();
?>
<script type="text/javascript">
var my_custom_js_block_info = <?php echo $h->jsonEncode($info); ?>;
</script>
(untested, top-of-my-head code, but should work)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With