1

Can I access the value of a javascript function from outside the function like if I had a function

<script>
function test_tree(opt)
{
    val = opt;
}
</script>

Can I access the val value from outside the test_tree function or is there a way to access it from PHP code?

I need to be able to access a value from the javascript code in PHP code.

hakre
  • 193,403
  • 52
  • 435
  • 836
jarus
  • 1,853
  • 11
  • 44
  • 76
  • possible duplicate of [Pass a PHP string to a Javascript variable (including escaping newlines)](http://stackoverflow.com/q/168214/), [How to pass a variable / data from javascript to php and vice versa?](http://stackoverflow.com/q/406316/90527) and many others (depending on exactly what jarus is asking for). – outis Feb 13 '12 at 12:37

2 Answers2

4

Considering that you didn't use var to declare the variable it is available to every function and all code in the global scope and beyond because without the var the variable is created in the global scope.

Answering your question though, if you want the variables created inside a function to exist beyond the life of a function, use a closure. You could give the variable to some object accessible outside the function which has the job of storing a bunch of these values.

If you want the variable (created in JavaScript and therefore I assume on the client) to be accessible to your PHP back end you'll have to send a request to your server. Probably an ajax call if this execution isn't part of submitting a form.

Bjorn
  • 69,215
  • 39
  • 136
  • 164
1

Set the value to a hidden field, and read hidden field in your server side code.

<input type="hidden" id="myVariable">

In your function :

document.getElementById('myVariable').value = val;
Canavar
  • 47,715
  • 17
  • 91
  • 122