最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Calling Javascript function in PHP while passing PHP variables into the function - Stack Overflow

programmeradmin1浏览0评论

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
  • 2 echo "<script type='text/javascript'>functionName($var1, $var2, $var3);</script>"; – aldrin27 Commented Sep 19, 2015 at 9:05
  • Your I've change your quotes. – aldrin27 Commented Sep 19, 2015 at 9:06
  • That was the actual quotes I was using in my code, does it have any difference? – Ramtin Soltani Commented Sep 19, 2015 at 9:07
  • 1 Yes because single quotes litterally puts your $var as $var. While double quotes puts your $var in 0 1 or 2 – aldrin27 Commented Sep 19, 2015 at 9:08
  • I'll make this my answer. Can I? And mark that as green check? – aldrin27 Commented Sep 19, 2015 at 9:09
 |  Show 4 more comments

2 Answers 2

Reset to default 12

Single quotes litterally puts your $var as $var. While double quotes puts your $var in 0 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>"
发布评论

评论列表(0)

  1. 暂无评论