1

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>

3 Answers3

1

Try something like this:

<?php $myVar = 5; ?>
<head>...</head>
<body>
    <script>
         var myVarFromPHP = <?php echo $myVar; ?>;
    </script>
    ...
</body>

Try seeing this stackoverflow answer as well

Community
  • 1
  • 1
Nathan
  • 1,321
  • 1
  • 18
  • 32
0

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>
camelCase
  • 5,460
  • 3
  • 34
  • 37
0

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>