0

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>
4
  • 1
    Is there any errors in the console? Commented May 24, 2017 at 9:44
  • check browser developer tools console - also the view page source as the browser gets it (ctrl-U) Commented May 24, 2017 at 9:44
  • document.write - welcome to the 21st century, time traveller :p Commented May 24, 2017 at 9:45
  • I assume that echo $js_array and echo "var javascript_array = ". $js_array . ";\n" do not work so well together. Commented May 24, 2017 at 11:47

4 Answers 4

0

You can simply do

<script>
    document.write("aa");
    var js_array = '<?php echo json_encode($podaci); ?>';
    document.write("var javascript_array = "+js_array);
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

Comments

0
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.