0

I am trying to learn javascript. I have the following code:

<?php
    $a = true;
    $b = false;
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
        window.variable = {
            a: <?php $a ? true : false ?>,
            b: <?php $b ? 1 : null ?>
        }

        console.log(variable);
    </script>
</body>
</html>

Javascript is not accepting the true, fasle, 1 or null I am getting the Uncaught SyntaxError: Unexpected token , and it is displaying the following in the chrome dev tools:

<script>
    window.variable = {
    a: ,
    b:      }

    console.log(variable);
</script>

where am I going wrong??

Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72

2 Answers2

1
a: <?php $a ? true : false ?>,
b: <?php $b ? 1 : null ?>

First, you're not outputting anything. You need to echo things.

Second, the string representation of false is an empty string. Same thing for null. So, even with echo, you'll get empty outputs for some values of $a and $b, and the same JS syntax error.

You can fix the output by outputting the strings true, false, and null:

a: <?php echo $a ? 'true' : 'false' ?>,
b: <?php echo $b ? 1 : 'null' ?>

but for a more resilient approach, since you're outputting for use in JavaScript, use json_encode instead:

a: <?php echo json_encode($a ? true : false) ?>,
b: <?php echo json_encode($b ? 1 : null) ?>

or, even better, have PHP output the whole JS object:

window.variable = <?php echo json_encode([
    'a' => $a ? true : false,
    'b' => $b ? 1 : null,
]); ?>;
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
0

Remember that you're building text; use "echo" to output the right value as a string.

<?php
  $a = true;
  $b = false;
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
    <script>
        window.variable = {
            a: <?php echo $a ? "true" : "false" ?>,
            b: <?php echo $b ? "1" : "null" ?>
        }

        console.log(variable);
    </script>
</body>
</html>