3

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?

9
  • 2
    echo "<script type='text/javascript'>functionName($var1, $var2, $var3);</script>"; Commented Sep 19, 2015 at 9:05
  • Your I've change your quotes. Commented Sep 19, 2015 at 9:06
  • That was the actual quotes I was using in my code, does it have any difference? 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 Commented Sep 19, 2015 at 9:08
  • I'll make this my answer. Can I? And mark that as green check? Commented Sep 19, 2015 at 9:09

2 Answers 2

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>"
Sign up to request clarification or add additional context in comments.

Comments

3

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

Thanks. I have a question if you don't mind. When one of my variable contains new lines, the function doesn't get called. I tried nl2br() but it didn't help. Any ideas?
Can you post the full source somewhere?
the full source is unnecessary because it's too big. I actually solved the problem by replacing all the newlines with <br/>. To demonstrate the problem, just define a variable in php, and set its value to a textarea's text value (and make sure you have newlines typed in the textarea). Then try to pass that variable to a javascript function. You'll see that the function would never be called. Try the same thing with a textarea without any newlines and it works perfectly. Once again I have already solved this but I don't get the logic of the function never getting called.
Strange, nl2br() works for me ... Can you give at least the text which contains newline special characters?
The text varies based on user input. It's just simply any text containing a line break.
|

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.