Calling Javascript function in PHP while passing PHP variables into the function

15,420

Solution 1

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>"

Solution 2

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>"
Share:
15,420
Ramtin Soltani
Author by

Ramtin Soltani

I do backend programming with Node JS and Express, Frontend with Angular, cross-platform mobile development with NativeScript and Angular, and cross-platform desktop development with Electron and Angular. I also do UI, UX, and logo design with Adobe Photoshop CC, Adobe Illustrator CC, and Adobe XD CC.

Updated on June 04, 2022

Comments

  • Ramtin Soltani
    Ramtin Soltani almost 2 years

    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?