Reputation: 94
How to pass a value from php to javascript? I'm working with smarty and i tried this but js seems to take it as a a string. The value is set to 20.
$smarty->assign('settings', $settings); //$settings is an array
$settings is coming from an file, basically it are some settings. i want to select an option in an html doc with that value but it is not working.
<select id="entrys">
<option>5</option>
<option>10</option>
<option>20</option>
</select>
and in the js file then:
$(document).ready(function()
{
$('#entrys').val("{$settings['frontendEntrys']}");
});
But no option is selected then not even the first or default value and if i try to print {$settings['frontendEntrys']} it's also not working. It just seems to be taken as a string.
BTW: Is it a good way to pass some settings with smarty or generally? How can i pass the values if i don't use smarty? Would this be correct? Is this a good way, if it's done in an html file?
<script>
var data = <?php echo $settings['entrys']; ?>
</script>
Upvotes: 2
Views: 1841
Reputation: 1563
In smarty you can use: {$myarray|@json_encode}
Howto generate json with smarty?
So it would be probably something like this:
<script>
var data = {$settings|@json_encode}
</script>
Then you can access that in js like normal object data.entrys;
less php/js mishmash more clear js code.
$('#entrys').val(data.entrys);
Upvotes: 3
Reputation: 9782
You could use this approach, which has the added advantage of synchronizing the HTML and .ini settings.
<select id="entrys">
{foreach $settings as $setting}
<option {if $setting == 'frontendEntrys'}selected{/if}>{$setting}</option>
{/foreach}
</select>
Upvotes: 1
Reputation: 89
Define a global JS variable on your Smarty template file :
<script>
_Entrys = {$settings['frontendEntrys']};
</script>
And use on JS file :
$(document).ready(function()
{
$('#entrys').val(_Entrys);
});
Upvotes: 1