3

My php generates some type from the DB and it is passed to a Smarty Variable $X.

With the help of Jquery, I want to be able to click a button, and the content of one of my div will be be replace with $X.

$(document).ready(function(){
  $("button").click(function(){
    $("#div1").html($X);
   });
});

This piece of Jquery script is included in an external js file.

1 Answer 1

4

If you have a template file that is parsed where you can output PHP->Smarty assigned variables, something you could do is create a global JS variable in the template, and then use that global variable within your JS as normal.

Such as:

Template file

<script type="text/javascript">
var MyGlobalVar = "{$MyGlobalVar}";
</script>

Global.js file

$(document).ready(function(){
    $("button").click(function(){
        if (MyGlobalVar != '') {
            $("#div1").html(MyGlobalVar);
        } else {
            alert('Error! Error! Abort!');
        }
    });
});

Note, you could output the Global.js file with it being parsed by Smarty (although... this is probably not a great idea) and inject your PHP->Smarty variables this way. This would treat the Global.js included file as a Smarty template.

To do so, you would need to use {literal}, probably name the file with a .php file ending (so it was PHP-parseable), and add a PHP header() call so PHP outputs the file contents to the browser as a Javascript content-type.

Global.js

<?php

header("content-type: text/javascript");

?>
var MyGlobalVar = "{$MyGlobalVar}";
{literal}
$(document).ready(function(){
    $("button").click(function(){
        if (MyGlobalVar != '') {
            $("#div1").html(MyGlobalVar);
        } else {
            alert('Error! Error! Abort!');
        }
    });
});
{/literal}

Additionally, on the PHP side, you might want to consider adding slashes to your variable, especially if the JS variable will contain html or other bits of text that will use single/double quotes.

Sign up to request clarification or add additional context in comments.

2 Comments

That works like a CHARM! Very impressive. So my understanding is, if you want to use a smarty variable in JS, you have to pass it to a JS variable on the TPL page while the tpl is being parsed. I am now exploring passing it as a parameter, 'coz i dont like global variable
Yes, a Smarty variable is essentially no different from a PHP variable (Smarty compiles to PHP, for instance). All you need is some page to be parsed by your Smarty parser. Also, if this answers your question, please click the outlined arrow next to the question and below the vote count to accept it as the answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.