2

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>
Procos
  • 94
  • 9

3 Answers3

3

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);

Community
  • 1
  • 1
imclickingmaniac
  • 1,467
  • 1
  • 16
  • 28
1

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);
});
Kevin Pierson
  • 89
  • 1
  • 8
  • Correct, but this will only work if `$settings['frontendEntrys']` is number. In all other cases (string, array, object) you will get errors. – imclickingmaniac Mar 30 '15 at 12:02
1

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>
user2182349
  • 9,569
  • 3
  • 29
  • 41