David
David

Reputation: 21

Get config data to javascript file - magento

I have a really simple requirement but cant find a good solution to it.

How do I get config data into javascript files within magento. I need to load some config data from a module and make it available from within some javascript code. Without loading this data onto hidden fields on the page or using ajax to fetch them from a controller - how do i do this?

Thank you in advance for any help.

Upvotes: 2

Views: 5392

Answers (2)

Joe Mastey
Joe Mastey

Reputation: 27119

You can grab the value you are looking for like this:

// using seo as an example. look at the path field on core_config_data
$value = Mage::getStoreConfig("web/seo/use_rewrites");

Put this in a template that will echo your code:

<?php
$seo_value = Mage::getStoreConfig("web/seo/use_rewrites");
?>
<script type='text/javascript'>
magento_config = {}
magento_config['seo_value'] = "<?php print $seo_value; ?>";
// ... add more ...

</script>

Add that template to your layout and you will now have a global JS object called magento_config that you can use to grab your values. Depending on where you put your template, you may have to wait for the page to load before your variables are available.

Make sure not to echo these values indiscriminately, as there may be security implications in echoing store config data to the frontend.

Hope that helps!

Thanks, Joe

Upvotes: 2

kieran
kieran

Reputation: 2312

Add this code in before you load the JS...

<script type="text/javascript">var var_name = <?php echo $var_name; ?></script>

Then you can load in JS like

<script type="text/javascript" src="/js/file.js"></script>

In your file.js (providing that the file is loaded after the variable definition) you can do something like...

//execute as soon as DOM is loaded
window.onDomReady(onReady);

//do on ready
function onReady()
{
    alert(var_name);
}

Or if you were using jQuery

$(document).ready(function(){ alert(var_name); }

Upvotes: 0

Related Questions