Page 1 of 1
Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 2:58 pm
by Jessica
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.
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 3:07 pm
by Eran
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
Posted: Wed Jun 25, 2008 3:42 pm
by Jessica
Yes, I have turned the short-tags to "On", but the screen output is still "<? =$vartopass ?>".
What should be the reason? Thanks a lot.
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 3:47 pm
by Eran
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
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 4:42 pm
by Jessica
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.
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 4:57 pm
by Eran
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:
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 5:04 pm
by cybercog
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:
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;
?>
Untested but it should work.
- D
Re: Help please: Passing PHP values to Javascript
Posted: Wed Jun 25, 2008 5:09 pm
by Eran
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.