tags:

views:

141

answers:

4

How can I add php variable to javascript e.g:

onClick="javascript:alert('echo $name;')Click Me</a>***

but it is not working

i have not includey original becuse it is not showing original …!!

+8  A: 

The php looks fine, as long as the $name variable is set. Try this:

onclick="alert('<?php echo $name; ?>');"
Scott Saunders
Should work :) That's not how I understood the question at first, though ;)
Romain
Make certain the string is JS and HTML safe. htmlspecialchars will do the job for HTML, I've no idea what PHP has for JS though.
David Dorward
+1  A: 

Adding PHP variables to javascript can be done simply by using PHP's <?php and ?> open/close tags, like so:

<?php $var = 'Hello world!'; ?>
alert('<?php echo $var; ?>');

Alternatively, you can echo javascript code, including any vars. However, this is much less readable, and generally considered bad practice:

<?php $var = 'Hello world!';
echo "alert('$var');"; ?>

Edit: The example code you typed is nearly correct; all that you missed are the PHP opening and closing tags, as I used in my answer above.

Duroth
+1  A: 

Also try this:

onclick="var text = '<?php echo $name; ?>'; alert(text);"

otherwise unterminated string literal" error appear

Coyod
A: 

another way using short php tags and str_replace() function

onclick="alert('<?=str_replace("'", "\'", $name);?>');"

In your php.ini short_open_tag must be enabled or use normal approach using echo

onclick="alert('<? echo str_replace("'", "\'", $name); ?>');"

php.ini code:

short_open_tag = On
George