views:

764

answers:

2

How may I retrieve, by JS (and I mean an external script), the value of some variables assigned in a (php) include file like the one below?

<?php 
$var1 = "a";
$var2 = "foo";
?>
A: 

Assuming that you mean using an AJAX request to retrieve the variables...the best way to do that would be:

<?php
$array["var1"]="a";
$array["var2"]="foo";
echo json_encode($array);
?>

And on the JS end, you would want to do:

json = eval( "(" + response + ")" );

And var1 and var2 would be json.var1/json.var2


Edit:

In that case you should be able to do something like:

<script type="text/javascript">
    var phpvars = <?php echo json_encode($array); ?>;
<script>

And just place that above where whistle.js will be included, and then the Javascript in that file will be able to access the variables through phpvars. (Changing the variables.php file so that it has the same format as above, except no echoing of it).

Thomas
I'm afraid the "echo" statement would interfere with the HTML page (that's a third file) that includes/requires this PHP file? Sorry, I'm completely new to AJAX
Yopi
Okay so basically, the structure is "main.php" requires/includes "variables.php", and inside "main.php" there is Javascript? In that case you just need to include "variables.php" above where your javascript is, and echo it directly into the javascript. If the javascript is from a .js file, then you need to echo those variables into a script tag before that .js file and have it use those.
Thomas
uh-oh sorry, it's more like that:main.php requiring variables.php and calling whistles.js (respecting progressive enhancement);on click, whistles.js has to get some values from variables.php
Yopi
You can't `just get variables` from a PHP file using javascript. One server side, one's client side. Javascript cannot interact with PHP before it's parsed by the server, you need to find a way to display the variables as text.
Ian Elliott
A: 

To reiterate the previous feedback, PHP is used to generate HTML -- the PHP file itself is never available to the browser. You can use the variables.php to generate hidden tags, then JavaScript to read them.

eg,

variables.php output: foo javascript: document.getElementById('varA').innerText

or

variables.php output: javascript: document.getElementById('varB').value

DreadPirateShawn