Using smarty variable in jQuery function

My php generates some type from the database and is passed to the Smarty $ X variable.

With Jquery, I want you to be able to click a button, and the contents of one of my divs will be replaced with $ X.

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

This piece of jQuery script is included in the external js file.

+3
source share
1 answer

If you have a template file that is being processed, where you can output PHP-> Smarty variables, then you can create a global JS variable in the template and then use this global variable in JS as usual.

For instance:

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!');
        }
    });
});

: Global.js Smarty (... , , ) PHP- > Smarty . Global.js Smarty.

{literal}, , .php( PHP-parseable) PHP header(), PHP Javascript.

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}

, PHP , JS html , / .

+4

All Articles