简体   繁体   中英

Printing PHP variable using javascript

I am trying to print a dynamic database variable using javascript. My code is simple. i am using :

    var name = "<? echo $listname; ?>";
    var listName = 'ADD A MEMBER TO "' + name + '"';

What i get printed is: ADD A MEMBER TO "" < !--? echo $listname; ?--> (without the space). Im guessing for some reason the "<" character is a shortcut for it. Is there any way to bypass this ? I simply need it to print it without the < !-- -->.

Thank you in advance

This is usually only possible if your JavaScript code is inside a .php file. Your server might also need the opening PHP tag to be <?php as well. You can use <? as an open tag only if short_open_tag is configured. See http://www.php.net/manual/en/ini.core.php#ini.short-open-tag for more information on that.

Here's a quick example how I made this work running on PHP 5.4.15 in Windows 7:

// omg.php

<?php $listname = "win"; ?>

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>Stuff</title>
</head>
<script>
    var name     = '<?php echo $listname ?>';
    var listName = 'ADD A MEMBER TO "' + name + '"';
    console.log(listName);
</script>
<body>
</body>
</html>

The above sample should print ADD A MEMBER TO "win" in the console.

you have a syntax error in your opening php tag. in general, it is better practice to get the variable from ajax, but it is possible to use this method, though its not really a great practice. also, don't use double quotes in javascript code. ever.

var name = '<?php echo json_encode($listname); ?>';

edit:

its possible you're trying to add a php tag inside of a php statement that hasn't been closed. you need to use the concatenation operator if so.

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