5

How do I get access to php variables in Joomlas approach to integrate Javascripts with addScriptDeclaration?

$document = JFactory::getDocument();
$variable = "test";

$document->addScriptDeclaration('
    jQuery(document).ready(function () {
        var simple = "<?php echo $variable; ?>";
        alert(simple);
    });
);

The classic form of integrating php variables won't work.

6

Instantly see the issue here. What you basically doing is the following:

<?php    
    $var = 'foo';
    <?php echo $foo; ?>    
?>

You're using duplicate <?php tags which will cause issues.

Use the following instead

<?php
    $document = JFactory::getDocument();
    $variable = "test";

    $document->addScriptDeclaration('
        jQuery(document).ready(function () {
            var simple = "' . $variable . '";
            alert(simple);
        });
    ');
?>

You were also missing a closing single quote before the last bracket in your code which I've added for you.

  • Yes, this will do Lodder, thx. – Perino Feb 22 '15 at 7:31
-1

This is how you can get access to php variable inside javascript.

$document = JFactory::getDocument();
$variable = "test";

$document->addScriptDeclaration('
    jQuery(document).ready(function () {
        var simple =<?php echo json_encode($variable); ?>;
        alert(simple);
    });
);
  • 1
    You don't use <?php echo json_encode($variable); ?> inside <?php tags that are already there. $document = is already PHP, not Javascript. See my answer to get a better understanding – Lodder Feb 18 '15 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.