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>
...
2
  • 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. Commented Nov 23, 2012 at 13:14
  • 1
    The error must be somewhere else in your code, cause the output you are showing here is working. Commented Nov 23, 2012 at 13:19

3 Answers 3

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)

0

Simply try

<script language="javascript" type="text/javascript">
        alert(<?=$abc?>);
</script>
0

Try

var xyz="<?= echo $abc ?>";

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.