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.xmlfileAdding a template to your theme for the above block
To add the block to the layout via your
local.xmlfile, something like this should sufficeThen add the following folder and file to your theme
At this point you have a
phtmltemplate file that will be rendered on every page. You can add whatever javascript variables you want. I’m fond of a pattern something like(untested, top-of-my-head code, but should work)