0
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 ??

2
  • 3
    Post your actual code. This code will work. Commented Jan 25, 2012 at 19:32
  • Both works... jsfiddle Commented Jan 25, 2012 at 19:32

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

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.