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
200k55 gold badges454 silver badges868 bronze badges
asked Apr 12, 2009 at 7:29
1

2 Answers 2

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.

answered Apr 12, 2009 at 7:37
Sign up to request clarification or add additional context in comments.

Comments

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;
answered Apr 12, 2009 at 7:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.