0

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?

1 Answer 1

3

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:

https://www.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()

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

2 Comments

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

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.