Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access PHP variable in JavaScript [duplicate]

Tags:

javascript

php

Possible Duplicate:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Is there any way to get access to a PHP variable in JavaScript?

I have a variable, $a, in PHP and want to get its value in a JavaScript variable.

like image 280
sahil Avatar asked Nov 26 '10 17:11

sahil


People also ask

Can I access php variable in JavaScript?

Most of the time you will need to access php variables inside jquery or javascript. If you have simple string value then you can echo this in javascript directly but if you have array type of value and you want to get it in javascript then you have to use json encode method.

How set php variable in JavaScript?

Inside the JavaScript, we can use the PHP tag to echo the PHP variable assigning it to a JavaScript variable. For example, assign a value Metallica to a variable $var inside the PHP tags. Write a script tag and inside it, write a PHP tag. Inside the PHP tag, echo a JavaScript variable jsvar .

How pass data from JavaScript to php using AJAX?

click(function() { var userID = $(this). attr('id'); //alert($(this). attr('id')); $. ajax({ type: "POST", url: 'logtime.


2 Answers

You can't, you'll have to do something like

<script type="text/javascript">    var php_var = "<?php echo $php_var; ?>"; </script> 

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

like image 120
metrobalderas Avatar answered Oct 18 '22 15:10

metrobalderas


metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript"> var something=<?php echo json_encode($a); ?>; </script> 
like image 41
rhino Avatar answered Oct 18 '22 14:10

rhino