Hi,
I need to pass some PHP values to Javascript. I tried the following example:
<? $vartopass = "Hello"; ?>
<script = "javascript">
var strnewVar = '<?=$vartopass?>';
alert(strnewVar);
</script>
But the screen output is "<?=$vartopass?>" instead of "Hello".
What's wrong with my code? How to make it work?
Thanks a lot for any help.
Help please: Passing PHP values to Javascript
Moderator: General Moderators
Re: Help please: Passing PHP values to Javascript
Do you know if short_tags are turned on in your php configuration? Some setups only allow the full <?php tag to be used.
Re: Help please: Passing PHP values to Javascript
Yes, I have turned the short-tags to "On", but the screen output is still "<? =$vartopass ?>".
What should be the reason? Thanks a lot.
What should be the reason? Thanks a lot.
Re: Help please: Passing PHP values to Javascript
your last reply shows a space between the php tag and the equal operator '='
it needs to follow with no space '<?='
also space the variable from the tag
and if that doesn't work, simply use echo
it needs to follow with no space '<?='
also space the variable from the tag
and if that doesn't work, simply use echo
Re: Help please: Passing PHP values to Javascript
Thank you Pytrin,
I tried <?php echo $vartopass; ?> also, but this time the alert dialog didn't show at all. Do you know what the reason probably is?
Thanks a lot.
I tried <?php echo $vartopass; ?> also, but this time the alert dialog didn't show at all. Do you know what the reason probably is?
Thanks a lot.
Re: Help please: Passing PHP values to Javascript
It seems to me that short tags aren't working for you. In general I would recommend not to use short_tags (and the PHP manual recommends that as well).
Using a full php tag (<?php) before your variable declaration should probably solve your problem.
ie:
Using a full php tag (<?php) before your variable declaration should probably solve your problem.
ie:
Code: Select all
<?php $vartopass = "Hello"; ?>
Re: Help please: Passing PHP values to Javascript
Most of my work is generated dynamiclly into a template, but if I was doing simple pages, I probably would heredoc the entire HTML code and just put variables where I need them.
IE:
Untested but it should work.
- D
IE:
Code: Select all
<?php
$js_var1 = 'Hello World';
print <<<HTML
<html>
<head>
<title>$title_name</title>
<script>
document.write('$js_var1');
</script>
</head>
<body>
</body>
</html>
HTML;
?>
- D
Re: Help please: Passing PHP values to Javascript
what is the point of echoing html inside of PHP if there is no additional formatting? much better to write html directly in my opinion.