Reputation: 33
I want a variable that is in php to javascript function argument, but I do not get :( anyone can help me ..
//file js.js
function ComputeTotalPrice(first_meters_price){
alert(first_meters_price);//result undefined
}
<!DOCTYPE html>
<?php
...
$first_meters_price = price_type(get_geo_id("Rural"), //returns 4
?>
<script src="js.js" >
ComputeTotalPrice(<? echo $first_meters_price; ?>);
</script>
<head>
...
</head>
<body>
<div id='reserva'>
...
</div>
</body>
</html>
Upvotes: 1
Views: 64
Reputation: 33
like this works.. but is ot the best way to do this..
<!DOCTYPE html>
<html>
<body>
<?php $var_to_js = function_php();?>
<input type='text' class='hide' id='var_to_js' value='<?php echo $var_to_js; ?>'/>
<script>
var var_from_php = document.getElementById('var_to_js').value;
</script>
</body>
</html>
Upvotes: 0
Reputation: 5608
As others have mentioned and linked to external answers, content inside a script
tag is unreliable and even prohibited in some browsers when a src
attribute is included; as such, it should be avoided.
For this to operate properly, one approach would be to pull the function from js.js
into the script
tag like below. It's undesirable but it does function as needed.
<?php $first_meters_price = 4; ?>
<script type="text/javascript">
function ComputeTotalPrice(first_meters_price) {
alert(first_meters_price);
}
ComputeTotalPrice(<?php echo json_encode($first_meters_price); ?>);
</script>
Upvotes: 0