Passing var from php to javascript
I try to do something pretty strait... getting php value to javascript
he开发者_开发知识库re is the page
here is the code..
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php $imagepath; ?>
alert (whatisthepath);
</script>
ALWAYS getting UNDEFINE.... why ?
--
Final wordking optimized code :
alert ("<?php echo $_REQUEST["path"]; ?>");
Missing: quotes around the var, php output to js var, semicolon after var setting:
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = "<?php echo $imagepath; ?>";
alert (whatisthepath);
</script>
All strings in JavaScript need to be surrounded with quotes. For example:
var whatisthepath = "<?php $imagepath; ?>";
The other issue is that you are not actually printing the string. All the above line of code will result in is an empty set of quotes. The correct way to do it would be to echo
the imagepath
var whatisthepath = "<?php echo $imagepath; ?>"
For exactly this purpose, PHP offers the shorthand notation of <?= ... ?>
. To output to value of the variable $imagepath, you can use <?= $imagepath ?>
. For this to work, the short_open_path ini variable must be set to true. This may not be the default of your web server.
So, this turns the code into
<?php
ini_set('short_open_tag', TRUE);
$imagepath = SOME_VALUE;
?>
<script language="javascript">
var whatisthepath = "<?= imagepath ?>";
alert(whatisthepath);
</script>
Changing the ini value may not be convenient if it's just about a few variables, but if it happens more often in the code, I tend to find it make things more readable.
You forgot to add an echo or print statement in front of your $imagepath
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo $imagepath; ?>
alert (whatisthepath);
</script>
PHP is a serversided language while javascript is a client side language. Which means you have to threat it the same way you would threat HTML.
For example:
<div><?php echo $content; ?></div>
Hopefully this will give you a better understanding...
You can use json_encode()
to ensure that the variable is properly escaped and quoted etc. for javascript. e.g.:
<?php $imagepath = $_REQUEST["path"]; ?>
<script language="javascript">
var whatisthepath = <?php echo json_encode($imagepath); ?> ;
alert (whatisthepath);
</script>
You should use to ensure that the variable has correct JS syntax.
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo json_encode($imagepath); ?>;
alert (whatisthepath);
</script>
精彩评论