1

I've got a variable named allow which I want to be global, so any other function will be able to use it. What happens is, when I call the variable from a certain function, it returns undefined.

Here's my code:

var allow = null;

$('#form').submit(function(e) {
    error_found = false;

    $('#text').click();


    console.log(window.allow);

    if(window.allow == false) {
        alert('מספר הסדר שהוזן הינו בשימוש, נא בחר מספר אחר, או סדר את רשימת הסדר מחדש.');
        $("#order").focus();
        e.preventDefault();
        error_found = true;
    }

    if($("#fix_rel").val() == "" && !error_found){
        alert('נא בחר זמן יחסי או קבוע.');
        $("#fix_rel").focus();
        e.preventDefault();
    }

    if($("#fix_rel option:selected").val()=="rel" && !error_found){
        if(!$.isNumeric($("#order").val())){
            alert('מספר הסדר חייב להיות מספר!');
            $("#order").focus();
            e.preventDefault();
        }

    }
});


$('#text').click(function() {
    table = $("#table").val();
    order = $("#order").val();
    $.post('test.php',{table:table,order:order}).done(function(data) {
        if(data == "true") {
            window.allow = true;
        } 
        if(data == "false") {
            window.allow = false;
        }
        console.log(window.allow);
    });
}); 

I've been trying to solve it for the past 2 hours, and so far, I have NO clue.

Thanks in advance!

kfirba
  • 5,231
  • 14
  • 41
  • 70
  • Looks like this common question http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Nov 28 '13 at 07:42
  • 1
    Possible conclusions 1) data is neither "true" nor "false" or 2) window.allow is accessed *before* the post callback (which is asynchronous) completes or 3) it's set again to `undefined` somewhere (**hint: it's #2**) – user2864740 Nov 28 '13 at 07:42
  • Trying defining it as `window.allow = null`, `undefined` means it's not recognizing `window.allow` as a defined variable (it should print `null`) – Rob M. Nov 28 '13 at 07:43
  • Are you loading any other scripts that need to access the variable contents? One of the hardest things to get into my head when learning js was the order of script loading. – Daniel Park Nov 28 '13 at 07:44

2 Answers2

3

If you do this:

var allow = null;
console.log(window.allow);

and you don't see null in the console, then the ONLY possible explanation is that your definition of allow is not a global variable because there is some sort of outer function (such as $(document).ready() function or something like that.

If there is intervening code between the two statements, then additional possibility is that some other code is changing the value of the allow variable.


When you use var in front of a variable declaration, it defines that variable in the current scope. If the current scope is global, then the variable is a global variable. If the current scope is inside of a function, then that variable is defined as a local variable to that function.


You can probably fix your issue in one of two ways depending upon what you are trying to accomplish.

  1. You can declare your variable in the actual global scope so it becomes a global variable.
  2. You can assign your variable it's initial value with window.allow = null and not declare it otherwise. This will make it global no matter where you put this statement.
  3. You can let the variable be a local variable and refer to it only as allow, not as window.allow when using it.
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • what do you mean? if I declare a function inside the `document.ready()` it won't work as a global variable? – kfirba Nov 28 '13 at 07:51
  • @kfirba - if your `var allow` is inside the `document.ready()` callback function, then it is a local variable of that function, not a global variable. You can define a global variable by doing `window.allow = null` instead of using `var`. `var` defines a function in the current scope. If the current scope is NOT global, then the variables defined with `var` are not global. – jfriend00 Nov 28 '13 at 07:52
  • +1 for *reasoning* against the output value being reported as `undefined`, even though it's likely orthogonal to the not-assigned issue (the code only seems to use `window.allow`). – user2864740 Nov 28 '13 at 07:53
  • Thanks a lot! I've learned a new thing. – kfirba Nov 28 '13 at 07:55
  • @jfriend00 very nice answer! However, for explanation sake, perhaps call `allow` a private variable of `$(document).ready`? – Dom Nov 28 '13 at 07:57
  • @jfriend00 I've made some changes to my code, accordingly to the link that I've given above, seems like it didn't help. I'm posting the new code now – kfirba Nov 28 '13 at 08:02
  • 1
    @kfirba - This site does not work very well when you post a question, we answer it and then you edit the question to an entirely different question that would need an entirely different answer. If you want to move on to a new issue that is different than the `window.allow` issue, you really ought to put your question back the way it was (you can revert using the edit link) and then start a new question. – jfriend00 Nov 28 '13 at 08:27
1

Use only allow instead of window.allow.

Like:

console.log(window);

instead of

console.log(window.allow);
codingrose
  • 15,563
  • 11
  • 39
  • 58
  • 6
    Unless there is an outer function that is not shown, this will not make a difference. – user2864740 Nov 28 '13 at 07:43
  • @downvoter would appreciate comment – codingrose Nov 28 '13 at 07:44
  • Thanks for the answer! unfortunately, I've already tried that. My attempt was to try and use the `window.allow`. BTW I think I got something, it seems like the variable is updating in `delay`. When I first submit the form, the value is `undefined` since i set it to be `null` but on the second submittion, it will be true/false according to the **first** attempt, if my **second** attempt is FALSE, the var `allow` will store the value `false` only on the **THIRD** submittion. Any idea how to solve this? – kfirba Nov 28 '13 at 07:45
  • @kfirba Yes, follow the related question that is now linked. – user2864740 Nov 28 '13 at 07:46
  • @user2864740 I've looked at it, but couldn't really understand what I change in my code to make it work based on the given answer – kfirba Nov 28 '13 at 07:50
  • @kfirba *Only* use the variable *after* it has been assigned - which is only guaranteed *after* the (XHR) callback runs. That is, when the (XHR) callback completes, do the actions then that depend upon the (now updated) `allow` value. – user2864740 Nov 28 '13 at 07:51
  • @Hiral—not my down vote, but you probably got it because your answer is more likely to cause issues than to solve them. `window.allow` will unequivocally access the global *allow* variable, whereas the unqualified *allow* may resolve to an identifier on a local variable object (i.e. not the global *allow*). – RobG Nov 28 '13 at 07:54
  • I've made some changes to my code, please view it and try to help me – kfirba Nov 28 '13 at 08:06