views:

71

answers:

1

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?

+2  A: 

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

JasonWoof
Hmm yeah, interesting. I never actually have a need to push that much data into the JS scope so I never thought of using JSON in the template. Actually a good idea. Cleaner. Thanks.
Spot
oh, also you can get rid of that document.ready stuff, and just set a js global. You've got the value before the js is even parsed, so you don't need to wait for anything before you can set it. Simply: var fromphp = $js_val (where $js_val is expanded by PHP)
JasonWoof
Yeah, good point. Thanks.
Spot