How do you access a PHP variable with JavaScript? [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 months ago.
I have a PHP file that creates a randomized string stored in a variable. I want to access this variable with JavaScript but the methods I've found online doesn't seem to be working. This is the code I have so far:
var test = "<?php echo json_encode($myVariable); ?>";
alert(test);
$myVariable is just a string: "testing".
I thought "testing" would be alerted but instead the code itself is (<?php echo json_encode($myVariable); ?>). When I take away the quotations, nothing happens. I'm very new to JavaScript so I'm not sure what's wrong. Is there another way I can access a PHP variable with JavaScript?

you can transfer variable contents by this
var test = "<?php echo $myVariable; ?>";
alert(test);

There are few way of accessing variables from php with javascript AJAX/Cookies/_SESSION or echo directly to javascript.
AJAX
Is more readable with better separations between layers it also allows for async transfer. BUT it can be very slow adding HTTPrequest can lead the website to slow down alot if there is alot of variable to request from php.
Cookies
I dont recommend it as there will be alot of necessary data store on the client side.
_SESSION
I recommend you using _SESSION as new developer will find it easier to use. it works similar to cookies but the only difference is once the page is closed the data is erase.
Echo directly to javascript
Easy to implement but horrible code practise.
All the above answers I explain quite vague do your research on topics, look for _SESSION to start with then move on to AJAX if appropriate.
Code example
PHP
if you are getting data from mysql
$_SESSION["AnyVariable"] = my_sql_query ("SELECT someData FROM someTable")
Or if its just a variable in PHP
$SESSION["aVariable"] = whateverValue;
JavaScript
<script type="text/javascript">
function someFunction()
{
var someVariable = '<%= Session["phpVariableSessionName"] %>';
alert(someVariable);
}
</script>

json_encode produces output ready for javascript, you must not put it into quotes:
var test = <?php echo json_encode($myVariable); ?>;

Try it the other way around ...
<?php echo "var test = '" . json_encode($myVariable) . "';"; ?>

Related

how to use PHP variable in Javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I am developing a web application in php, and I've used javascript many times. Now I need to use a php variable in javascript.
For example, a variable generated from a SQL query return, or a session variable, which are needed in the javascript section.
What is the best way to use a php variable in javascript?
Maybe you could do something like:
<script>
var a = <?php echo $a; ?>; //for numbers
</script>
That's one basic way of accomplishing what you want.
EDIT: As JiteshNK also pointed out, you could also do:
<script>
var a = <?php echo json_encode($a); ?>; //safest solution
</script>
You can do something like this :
If a normal variable:
<script type= "text/javascript">
var a = <?php echo $var; ?>;
</script>
OR
If you have json :
<script type= "text/javascript">
var a = <?php echo $json_encode($var); ?>;
</script>
If its simple string variable then use.
<script>
var a = "<?php echo $var; ?>";
</script>
If php variable is array then
var resultArray = <?php echo json_encode($varArr); ?>
// Use resultArray values in javascript
$.each(resultArray, function(index, value) {
}
I don't fully understand what you are trying to do.
Basically, I don't thing what you would like to do is possible.
Reason: JavaScript is running in the browser. At the time when your JavaScript code is executed, the page has already been loaded. At that time, there is no such thing as PHP available anymore. Your browser only knows about HTML.
PHP is running on the server and is used to "construct" or "build" or "compile" your HTML page.
What you definitely can do is: You can use PHP to create your JS code dynamically (like you already do that with your HTML file) and there use PHP to populate a JS variable with the contents of a PHP variable.

Get php variable in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I'm writing mostly in PHP, but one function requires me to use JavaScript. I need to access a PHP variable in my JavaScript. I've placed the following code between the <head> tags:
<script>
$(document).ready(function(){
$(document).keyup(function(e) {
if ($('.pho_big').is(':visible') && e.keyCode==27) {
var js_link = '<?php echo $p_link; ?>';
window.location.href = js_link;
}
});
});
</script>
In short, when the esc key is pressed, I want to go to $p_link. So I'm trying to copy $p_link to js_link and go there. Instead of getting the contents of $p_link, my browser is trying to go to <?php%20echo($p_link)%20?>, which is obviously incorrect.
I've already gone here, here, and here, all of which seem to tell me to do exactly what I'm doing. My knowledge of JavaScript is near zero, so I'm probably missing something simple, but I don't know enough to know what or troubleshoot.
it looks like <?php echo $p_link; ?> is not interpreted by php.so js_link contains string <?php echo $p_link; ?>.when you set window.location.href to <?php echo $p_link; ?> . browser tries to go to [less_than]?php%20echo($p_link)%20?[greater_than] which is url encoding of <?php echo $p_link; ?>.
(sorry,since I have low reputation, I cant post comment)

PHP var in javascript? [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 8 years ago.
I am trying to use a php variable in my javascript code, but i cant seem to get it working. Here is my js and php code:
<?php $s = "woo"; ?>
var images = <?=$s?>;
What i want to achieve, is a php variable in javascript ENCLOSED with ['']; With other words, so that the javascript code reads it like this: ['woo'];
I could really need some help, as i am very new to javascript. Thanks in advance.
I recommend using json_encode for all values "passed" to JavaScript - this will prevent against injection, accidental or otherwise. It also trivially handles quotes and allows complex object graphs to be supplied. If not already, I imagine that images is really, or should be, an array ..
var images = <?= json_encode($s) ?>;
Or
var images = <?php echo json_encode($s); php?>;
Look at the actual HTML to see what is being emitted, and that it is valid - the original yields JavaScript akin to var images = woo;, which will result in a ReferenceError (on woo).
One trick you can use is this, when you are inside a .js file it can be helpful, because php doesnt work.
Put the value of your php value inside a div as content, and then grab that in the javascript.
in the php file:
<div id="sVar" style="display:none;"><?php echo $s; ?></div>
in js:
var images = document.getElementById('sVar').innerHTML;

What is the best practice to assign php variable to javascript variable? [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
I have some code like this
var minAmountPay = <?php echo $this->chat['Current']['admin'] >= 1 ? 1 : $this->minAmountPay; ?>;
var userId = <?php echo $this->currentUserId?>;
I use ZF and I have a lot of javascript code in my action files. I want to create js-files for each action and do minifications of this files. But I can't create js-file because I have assigning php variable to javascript variable.
Maybe I need to use some javascript framework for this purposes?
Use data attributes.
For example :
HTML :
<div id="something" data-minamountpay="<?php echo $this->chat['Current']['admin'] >= 1 ? 1 : $this->minAmountPay; ?>"></div>
JS (with jQuery) :
var minAmountPay = $('#something').data('minamountpay');
JavaScript cannot directly interact with PHP.
This is because JavaScript is client-side, and PHP is server-side.
The only way to do this is as you have - by producing output in PHP which is put into the script.
you can add javascript to your html file by using
<script type="text/javascript">
var minAmountPay = <?php echo $this->chat['Current']['admin'] >= 1 ? 1 : $this->minAmountPay; ?>;
var userId = <?php echo $this->currentUserId?>;
</script>
You can assign these values to hidden inputs in your page.
And get the values by input value.
These values are visible to the user either way.
You might want to think about where you're putting those variables. Can you put them in the HTML instead? When I need to do what you are doing I use the HTML 5 data attributes and assign the variables to appropriate places like this:
<div id="my-appropriate-div"
data-min-amount-pay="<?php echo $this->chat['Current']['admin'] >= 1 ? 1 : $this->minAmountPay; ?>"
data-user-id="<?php echo $this->currentUserId ?>">
Then in JavaScript you can access the data thusly:
var minAmountPay = $('#my-appropriate-div').data('min-amount-pay');
var userId = $('#my-appropriate-div').data('user-id');
Obviously rather than putting them into variables, I just use them directly where needed in my functions.

how to make define php usable in js too [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a js function that make some ajax post and a php handler that parse the $_POST and do something. I would use in js and php the same constants. For example if i put some define in php:
define('done','1',TRUE);
I would like to have it on js too. Are there some way to have some constants declared one time and usable in all this 2 languages?
Define your constants in PHP but output them to your javascript by either writing them to an index.php master file (or similar) or fetch them by ajax
Use get_defined_constants to retrieve all constants and parse that to json
ie (I am without environment at the moment and unable to test this)
<script type="text/javascript">
var constants = <?php echo json_encode(get_defined_constants()); ?>
</script>
Have a look at the documentation on get_defined_constants how to retrieve your personal constants, http://php.net/manual/en/function.get-defined-constants.php
You could write your js in a PHP file and use your function returns echo'd out in your javascript i.e.
<?php
$someid = 'wrapper';
?>
<script type="text/javascript">
document.getElementById("<?php echo $someid; ?>");
</script>

Categories