Question

Anyone have any clean patterns for getting php vars into the js scope?

Two ways I have done it before is either injecting it with an actual call from the base template inside a document ready wrapper.

(jQuery/Smarty Template)

{literal}
$(document).ready(function() {
    TargetClass.targetVar = {/literal}{$phpVar}{literal};
});
{/literal}

Also setting it to a tag and pulling that from the DOM once the JS executes.

HTML

<link id="phpVar" value="{$phpVar}" />  

JS

var phpVar = $('#phpVar').attr('value');  

.

Have any of you found a better method?

Was it helpful?

Solution

You can generate JSON very easily from php. This is a nice way to get a whole array (or even a tree of nested arrays) of data to javascript in one go.

You can put it in a <script> header, or fetch it async with ajax.

Here's the php docs:

http://us3.php.net/manual/en/ref.json.php

if you put the json directly into the code, then it's already in javascript format. If you get it back from an ajax request, it'll be one big string, and you can parse it by simply passing it to eval()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top