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);
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);
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 :)
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;
make a function maybe can help u. this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);