0

I am trying to pass a value from php to javascript. I understand one is server side and one is client side. I believe what I am doing should work fine:

PHP Code:

        echo "<script type = 'javascript/text'>var x = " . -119 . ";";
        echo "var y = " . 49 . ";";
        echo "</script>";

Javascript Code:

z = [ x, y ]

But I get the error x and y are undefined.

ewein
  • 2,695
  • 6
  • 36
  • 54

4 Answers4

3

Type is text/javascript, not javascript/text. Your browser is probably ignoring the unrecognized script type.

Also, make sure if you replace "-119" with a variable that you take care to prevent XSS attacks by ensuring your variable contains a number or properly escaping it.

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
2

The type should be text/javascript.

Also, you'll need to be sure that this script snippet is executed before the code that assignes [x,y] to z.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
0
<script type = 'text/javascript'>
var x = <?php echo($x); ?>
var y = <?php echo($y); ?>
</script>

Should work

Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74
0

Your type is wrong, it should be: text/javascript and not javascript/text

Adriaan Nel
  • 370
  • 1
  • 11