Options

Javascript Q? passing php var to script

edited January 2008 in Vanilla 1.0 Help
I don't know javascript, but I want to include a script I found online in an extension I'm working on. The thing is, I want to pass a Configuration setting to the script.

The script will be added through my extension with the ol' $Head->AddScript(). Will the following code correctly pass the value?

<script language="javascript" type="text/javascript"> function Example(value) { if (value==<?php echo $this->Context->Configuration['ExampleSetting']; ?>) { ... } } </script>

Thanks!

Comments

  • This is quite confusing: a <script> tag and using $Head->AddScript().
    This should NOT work if you put php code in a .js using $Head->AddScript() but then you don't need the <script> tag.
    In CommentLinks, I remember learning a good trick for solving this problem:
    // Pass the discussion info to the javascript. We hide the menus incase any were opened before page load completes. if ( strstr(strtolower($Context->BodyAttributes), 'onload=') ) { $Context->BodyAttributes = str_replace('onload="', 'onload="BaseUrl=\''. $Context->Configuration['BASE_URL'] . '\';DefaultFormat=\''. $Default . '\';InstalledFormats=Array('. $FormattersCSV . ');MenuTitle=\''. htmlentities($Context->GetDefinition('CommentLinks_Copy')) .'\';HideMenus();', $Context->BodyAttributes); } else { $Context->BodyAttributes .= ' onload="BaseUrl=\''. $Context->Configuration['BASE_URL'] . '\';DiscussionName=\''. htmlentities($Discussion->Name) . '\';DefaultFormat=\''. $Default . '\';InstalledFormats=Array('. $FormattersCSV . ');MenuTitle=\''. $Context->GetDefinition('CommentLinks_Copy') .'\';HideMenus();" '; }
  • OK, I see. I was intending to place the script inside a seperate .JS file. I guess I don't need to include the tags if I do that. I warned you I didn't know javascript. ;)

    But you're saying including the php code inside the .JS file still won't work? Is there some other way to include to php code in the .JS file (using $Head->AddScript())? Is there some other way to pass a $Configuration[] value to a .JS script?

    If it helps, what I'm trying to do is hide/show some text depending on whether the user picks a certain option from a selector. But the option value is dynamic, based on a $Configuration[] value.

    Thanks!
  • First, note that JS code is sometimes cached in the browsers. Beware.
    You could use a .js file linked with AddScript() for the static code, and use the previous onLoad trick to define some vars, as done in CommentLinks.
This discussion has been closed.