I'm experiencing a problem when calling a JavaScript function inside PHP code and trying to pass my PHP variables as parameters into the function. While it seems really simple to me, I can't figure it out by trying different syntax.
Here is a sample code which can demonstrate the problem:
<?PHP
$var1 = 0;
$var2 = 1;
$var3 = 2;
echo '<script type="text/javascript">functionName($var1, $var2, $var3);</script>';
?>
If I try to pass constants (e.g. "123") the function gets called and the value is passed, but when trying to pass the PHP variable, the function doesn't get called at all.
How can I do this correctly?
2 Answers 2
Single quotes litterally puts your
$varas$var. While double quotes puts your$varin0 1 or 2
echo "<script type='text/javascript'>functionName('$var1', '$var2', '$var3');</script>"
Comments
I think you should use curly braces to better distinguish variables in a string. Just wrap them like this:
echo "<script type='text/javascript'>functionName({$var1}, {$var2}, {$var3});</script>"
6 Comments
Explore related questions
See similar questions with these tags.
echo "<script type='text/javascript'>functionName($var1, $var2, $var3);</script>";$varas $var. While double quotes puts your$varin 0 1 or 2