Pass variable from php to js

I was really confused when I tried to transfer variables from php to js. everything is fine when I try to get the value using id
eg:

var name = $("#name").val(); 

but my question is: if I want to convert, for example, this variable:

 $id = 182938; //the id of the user 

to this variable:

 var id; 

this question may be dumb ... maybe easy for you, but not for me: p
I searched for it and found only something like this anywhere I searched:

 <?php $number = rand(); ?> <script language="javascript"> var num = <?php echo $number ?> </script> 

Does it have the same effect as decreasing the value?

Thanks!!

0
source share
3 answers

Not really. Encoding as JSON ensures that it is a valid JavaScript literal.

 var num = <?php echo json_encode($number) ?> 
+1
source

what the code does:

 <?php $number = rand(); //assign random number to $number. let say it "3" ?> //then these are printed on the page normally <script language="javascript"> var num = <?php echo $number ?> //the $number is echoed at this position </script> 

and then the browser receives:

 <script language="javascript"> var num = 3; </script> 
0
source

You need to generate syntactically VALID javascript. PHP can send text in ANY part of the page that it generates, but this does not necessarily mean that it is actually USABLE text. In your case, you forgot ; , so your generated javascript is actually a syntax error:

 var num = <?php echo $number ?>; ^--- missing 

The same thing happens when you output text. Consider where you store the username in a variable:

 <?php $name = "Miles O'Brien"; // <-- note the single quote ?> <script> var name = <? php echo $name ?>; </script> 

This WATCH OK, but it will generate another syntax error:

  var name = Miles O'Brien; 

there are no quotes around the entire line, and the inline quote will start the line in javascript, causing the JS interpreter to complain about the undefined variable "Miles", the undefined variable "O", and the string with an inexhaustible string.

Instead, PHP should have been:

  var name = <? echo json_encode($name) ?>; 

JSON encapsulation ensures that you insert syntactically valid Javascript values.

-1
source

Source: https://habr.com/ru/post/921278/


All Articles