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.

2 Answers 2

7

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.

0
-2

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
  • 2
    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
    Commented Feb 18, 2015 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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