Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, December 23, 2015

How to pass variable from php to javascript?

How to pass variable from php to javascript?


I want to pass a php variable to javascript. I have tried something but I am not sure if it is safe way to do.

      

Also people do it some thing like this

';  echo 'var name = ' . json_encode($name) . ';';  echo '';  ?>  

Which of the code is better in terms of safety. Is there any risk using first code? A little explanation will be enough. Thanks

Answer by AMY for How to pass variable from php to javascript?


Your both code will produce same result and there no safety issue in both case.

You can find tutorials about web server and web browser on google for more details. http://www.tutorialspoint.com/internet_technologies/web_servers.htm

Answer by Rahul Pratap Singh for How to pass variable from php to javascript?


Yep you are doing it right. There is no security issue in doing it the way you have done.

Answer by Thibaut Pietri for How to pass variable from php to javascript?


Never print a post or get variables without validation.

https://en.wikipedia.org/wiki/Cross-site_scripting

http://code.tutsplus.com/articles/data-sanitization-and-validation-with-wordpress--wp-25536

Answer by Parixit for How to pass variable from php to javascript?


First case:

This case if used if we want to simply assign string value in javascript variable.

  


Second case:

For this case, you should use json_encode() when you want to add some array in javascript variable.

 $_POST['name']);  echo '';  ?>  

And yes, echo whole javascript or just echo your variable will make no change in your output. Just make sure that your javascript variable has proper wrapper either ' or nothing in case of object;

Answer by Roel Suidgeest for How to pass variable from php to javascript?


Note that the Javascript code will break if $name contains quotes. Use the PHP function addslashes to avoid this:

  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.