0

I am echoing a javascript block using PHP like this...

echo "<script language='javascript' type='text/javascript'>
        jQuery(document).ready(function($){
            var $lg = $('#mydiv');
        });
";

But I am getting the following error message...

Notice: Undefined variable: lg 

When I inspect the source, the line that defines $lg looks like this...

var = $('#mydiv');

Any ideas why it is happening? Does the $ need escaping?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

3 Answers3

5

When using double quotes in PHP, variables are interpolated inside strings, for example:

$name = "Elias";
echo "My name is $name";

This will print My name is Elias.

If you want to use $ inside an string, you must escape it or use single quotes:

$name = "Elias";
echo "I love the variable \$name";
echo 'I love the variable $name';

Both echos will print I love the variable $name

Also, due to the use of double quotes, you are using single quotes to the html inside your string. This is an invalid HTML, though the browser parse it correctly. (Actually it's valid, sorry)

The right way to do it is to use single quotes to your string, or escaping the double quotes:

echo "<script language=\"javascript\" type=\"text/javascript\">";
// or
echo '<script language="javascript" type="text/javascript">';
Elias Soares
  • 9,884
  • 4
  • 29
  • 59
0

Yes, indeed, when you echo "-delimited strings in PHP then everything starting with $ is interpreted as a variable.

You need to escape the string like this:

echo "<script language='javascript' type='text/javascript'>
    jQuery(document).ready(function(\$){
        var \$lg = \$('#mydiv');
    });";

To be safe, you should escape all $s in the string.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

When using double quotes php interpolate variables, so it's trying to evaluate $lg, that's why it's not showing on the output.

If you change to single quotes on the echo, it should work.

Or simply escaping $ with a backslash (\) on a double quotes string.

GMachado
  • 791
  • 10
  • 24