-2

I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?

var b = <?php echo $tagValue;?>;
        alert("B is " +b);
Manx_Warrior
  • 99
  • 10
  • 2
    is this a `.js` file, a `.php` file, or a `.js.php` file? if it isn't a `.php` file, this won't work – user2415992 Oct 24 '14 at 05:32
  • 1
    Also - easier way to pass a PHP variable to Javascript would be through a hidden field – user2415992 Oct 24 '14 at 05:34
  • "this code is giving me syntax error" and why don't you post your error? – Dinistro Oct 24 '14 at 05:34
  • 4
    if $tagValue is a string, you have to wrap it in a quote: b = ''; – Sachin Oct 24 '14 at 05:35
  • This is probably a duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – dawez Oct 27 '14 at 07:21

3 Answers3

3

You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:

var b = "<?php echo $tagValue;?>";
alert("B is " +b);

(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.

In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):

var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);

Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)

Zim84
  • 3,404
  • 2
  • 35
  • 40
  • 1
    You should mention that a variable containing the double-quote character will break the syntax of the javascript output. JSON encoding is much safer. – Jonathan Gray Oct 24 '14 at 05:43
1

Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;

Jonathan Gray
  • 2,509
  • 15
  • 20
-1

make a function maybe can help u. this is an example

// your php code  
$tagValue = 'value'; 
getValue($tagValue);
Eru
  • 51
  • 8