Javascript not loading when php in it

I have a problem when I open php tags inside script tags it doesn't load any of javascript code and when I remove php tags it works normaly.Why is that hapening?

<html>
<head>
</head>
<body>
<script>
    document.write("aa");
    <?php
    $js_array = json_encode($podaci);
    echo $js_array;
    echo "var javascript_array = ". $js_array . ";\n";
    ?>
</script>
</body>
</html>

Upvotes: 1

Views: 51

Answers (4)

Sir McPotato
Sir McPotato

Reputation: 959

echo $js_array;
echo "var javascript_array = ". $js_array . ";\n";

will give something like this : "[1, 2, 'foo', 'bar']"var javascript_array = [1, 2, 'foo', 'bar']; which is - obviously - an invalid javascript statement.

Just remove echo $js_array and it should work fine.

Upvotes: 0

Gautam D
Gautam D

Reputation: 330

Your code should like this

<html>
<head>
</head>
<body>
 <?php
    $js_array = json_encode($podaci);
  ?>
<script>
    document.write("aa");
    var javascript_array = '<?php echo $js_array; ?>';
</script>
</body>
</html>

Upvotes: 1

Gulmuhammad Akbari
Gulmuhammad Akbari

Reputation: 2036

Put your php tags in quotation:

<html>
<head>
</head>
<body>
<script>
    document.write("aa");
    var phpContents = '<?php $js_array = json_encode($podaci);?>';
    var javascript_array = "<?php echo $js_array;?> \n";
    alert(javascript_array);

</script>
</body>
</html>

Upvotes: 0

shubham715
shubham715

Reputation: 3302

You can simply do

<script>
    document.write("aa");
    var js_array = '<?php echo json_encode($podaci); ?>';
    document.write("var javascript_array = "+js_array);
</script>

Upvotes: 0

Related Questions