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 ??
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
myvarin 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 ofmyvarin the actual global scope (not inside any other function) or in the same scope as the function you’re trying to reference it from.