Evan Levesque
Evan Levesque

Reputation: 3213

Why I can't access variables from inside some functions (JavaScript)?

var myvar = "my value";

(function() {
  alert(myvar); // undefined
})();

or

  var myvar = "my value";
  $.post( url,
  function( data ) {
    alert(myvar); // undefined
  });

and how can I solve this issue without storing this value in a hidden input or div or other html containers ??

Upvotes: 0

Views: 4684

Answers (2)

Downpour046
Downpour046

Reputation: 1671

You can declare it as a global (which will work), but probably isn't the best practice when coding JavaScript for this purpose.

The best way to do it is to store the variable inside the function, at the top of the function

  $.post( url,
    function( data ) {
      var myvar = "my value";
      alert(myvar); // undefined
    });

If you're trying to use it across a multitude of functions, I recommend

(function($) {

     var myvar = "my value"; // To set this as a global, just remove the "var"

     $.post( url,
        function(data) {
          alert(myvar); // undefined
     });

})(jQuery);

Upvotes: 1

jfriend00
jfriend00

Reputation: 707876

If you put the variable in a scope that is reachable by the reference to it, it all works just fine. You can see that for your first example right here: http://jsfiddle.net/jfriend00/WvnvC/

So, you are apparently not showing us the whole picture and you have probably declared the variable in a scope that isn't available from your reference to it. We would have to see the real code or the actual scope to know what the issue is.

A common source of this problem is that you have defined myvar in a $(document).ready() handler (which is not the global scope) and then you are trying to refer to it from outside that $(document).ready() handler where it will not be reachable. Try putting the defintion of myvar in the actual global scope (not inside any other function) or in the same scope as the function you're trying to reference it from.

Upvotes: 2

Related Questions