I looked for appropriate answers for this on the smarty site, and the resounding answer was escaping javascript’s {}s with {literal}’s
Smarty template vars and Javascript functions
How to use Javascript codes in template files?
Access Smarty value with javascript
They basically all say to do something like this:
// $question_ids_json = ["1","2","3","4","5"] {literal} <script> $(document).ready(function(){ var question_ids = {/literal}{$question_ids_json}{literal}; alert(question_ids[0]); }); </script> {/literal}
So they want to put everything in a literal tag, and then basically escape that literal tag when smarty needs to be used.
I didn’t like this, so I put the value in a hidden input and then just retrieved that input in the javascript, thereby keeping the js clean of smarty shenanigans:
<input type="hidden" id="question_ids" value='{$question_ids_json}'/> <script> $(document).ready(function(){ //var question_ids = {$question_ids_json}; var question_ids = eval($('#question_ids').val()); alert(question_ids[0]); }); </script>
But this is just a matter of personal preference.
Hello,
Thanks For this article, however no one of those parts of code work.
For example for the second code i get the error:
TypeError: question_ids is undefined
[Stopper sur une erreur]
alert(question_ids[0]);
Do you know why?
Thanks for your help.
both code examples depend on you sending the smarty template $question_ids_json = [“1″,”2″,”3″,”4″,”5”];
That’s probably the problem you’re having.
Thanks that’s work good.
thanks it works