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
  • 3
    stackoverflow.com/questions/6528325/… second answer Commented Nov 23, 2015 at 19:02
  • 1
    Also might need <?php Commented Nov 23, 2015 at 19:04
  • 2
    <script src="js.js" > needs to be <script type="text/javascript"> Commented Nov 23, 2015 at 19:04

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@AlbertoSetim Hmmm... When you say it didn't work did it throw an error?
@AlbertoSetim Also, try not using <script src="..."> var myVar = <?php ... ?>; </script> and instead use two separate script tags.
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.