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?
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?
Share Improve this question asked Sep 19, 2015 at 9:04 Ramtin SoltaniRamtin Soltani 2,7103 gold badges28 silver badges45 bronze badges 9 | Show 4 more comments2 Answers
Reset to default 12Single quotes litterally puts your
$var
as$var
. While double quotes puts your$var
in0 1 or 2
echo "<script type='text/javascript'>functionName('$var1', '$var2', '$var3');</script>"
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>"
echo "<script type='text/javascript'>functionName($var1, $var2, $var3);</script>";
– aldrin27 Commented Sep 19, 2015 at 9:05$var
as $var. While double quotes puts your$var
in 0 1 or 2 – aldrin27 Commented Sep 19, 2015 at 9:08