-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);
5
  • 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 Commented Oct 24, 2014 at 5:32
  • 1
    Also - easier way to pass a PHP variable to Javascript would be through a hidden <input> field Commented Oct 24, 2014 at 5:34
  • "this code is giving me syntax error" and why don't you post your error? Commented Oct 24, 2014 at 5:34
  • 4
    if $tagValue is a string, you have to wrap it in a quote: b = '<?php echo $tagValue;?>'; Commented Oct 24, 2014 at 5:35
  • This is probably a duplicate of How to pass variables and data from PHP to JavaScript? Commented Oct 27, 2014 at 7:21

3 Answers 3

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 :)

1
  • 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. Commented Oct 24, 2014 at 5: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;

-1

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

// your php code  
$tagValue = 'value'; 
getValue($tagValue);
1
  • This is not answering the question. Commented Oct 27, 2014 at 8:21

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.