tags:

views:

265

answers:

2

can we 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 to php code how can i do this?

A: 

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
+4  A: 

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.

apphacker