0
    var desc;
    $.ajax({
        url: "data/step2.xml",
        dataType: "xml",
        success: function(data){
            $(data).find('date').each(function(){
                var day = $(this).find('day').text();
                var date = $("#txtDate").datepicker("getDate");
                date = (date.getDate()+"-"+date.getMonth()+1+"-"+date.getFullYear());
                if (day==date){
                    $(this).find('availability').each(function(){
                        var prod = $(this).find('product').text();
                        var time = $(this).find('starttime').text();
                        if (prod==label){
                            desc="!";
                        }
                    });
                }
            });
        }
    });

I'm having some issues accessing the desc variable... I want to manipulate it's value as you can see in desc="!", but it returns undefined. Isn't there any way to make the variable global or something? or some other way to access it? ... Oh, and all this code is inside a function.

6
  • 1
    $.ajax is async by default. Looks like you are trying to access desc before the ajax call completes. Commented Mar 1, 2013 at 18:21
  • First are you sure your code is run up to desc="!"? Commented Mar 1, 2013 at 18:24
  • You say "all code is inside a function..." which function? Is it all inside the success function? Commented Mar 1, 2013 at 18:24
  • @techfoobar: but the desc = "1" is INSIDE the success: handler, so by definition the assignment wouldn't happen until after the ajax results come in anyways. Commented Mar 1, 2013 at 18:24
  • Yes, checked with console.log Commented Mar 1, 2013 at 18:26

2 Answers 2

2

In this particular case the problem is not the scoping of the desc variable. The desc variable you manipulate in the success callback is the same one declared before the ajax call.

The problem here is timing. The success method doesn't execute at the same time the ajax call is made. It executes some time later when the ajax call completes. Only at that point is the value written to desc. Any code which handles the desc value must be called from the point where the desc value is set

if (prod == labe) { 
  desc = "!";
  onDescChanged();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, got it. Thank you! I'll try something else :)
0

I assume your code is attempting something like:

function foo() {
    var desc;
    $.ajax({
        ....
        success: function() {
            ...
            desc = "!";
        }
    });
    return desc; // this will return undefined, as success() hasn't completed
}

To counter this, use a callback function as in JaredPar's answer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.