0

I am wondering why I don't get an alert message with the javascript code below. It seems that the variable xyz is not recognized/defined? I can't find the mistake... Thank you very much for your help!

main.php

<?php
...
$abc="http://www.path.de/image.jpg";
...
?>    

<script type="text/javascript">
            var xyz="<?= $abc ?>";
</script>


<script language="javascript" type="text/javascript">
        window.alert(xyz);
</script>

No Alert message! Browser Output in source view:

...
<script type="text/javascript">
        var yxz = "http://www.bla.de/asd.jpg";
</script>


<script language="javascript" type="text/javascript">
        window.alert(yxz);

        </script>
...
Franc
  • 67
  • 1
  • 7
  • The browser doesn't know how you generated your JavaScript code so the PHP bit is irrelevant. You're probably defining `yxz` inside a block or function and calling it somewhere else out of scope. – Álvaro González Nov 23 '12 at 13:14
  • 1
    The error must be somewhere else in your code, cause the output you are showing here is working. – Jean Nov 23 '12 at 13:19

3 Answers3

1

This works:

<?php
$abc="http://www.path.de/image.jpg";
?>

<script type="text/javascript">
      var xyz="<?php print $abc; ?>";
</script>

And, please, remember to use json_encode() function to be sure, that you won't screw up the javascript:

Pass a PHP string to a JavaScript variable (and escape newlines)

Community
  • 1
  • 1
user4035
  • 22,508
  • 11
  • 59
  • 94
0

Simply try

<script language="javascript" type="text/javascript">
        alert(<?=$abc?>);
</script>
vivek salve
  • 991
  • 1
  • 9
  • 20
0

Try

var xyz="<?= echo $abc ?>";
toxicate20
  • 5,270
  • 3
  • 26
  • 38