简体   繁体   中英

adding php to javascript

How can I add php variable to javascript eg:

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

but it is not working

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

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

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

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.

Also try this:

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

otherwise unterminated string literal" error appear

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM