Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Accessing a variable whose value is set in an AJAX function

I've got a problem. I've been trying to solve the problem of how to avoid using global variables. I decided to use an object with functions on it instead, and wrote a script accordingly. However, the script won't run as expected:

GetXML: function() {
        $.ajax({
            type: "GET",
            url: "questions.xml",
            dataType: "xml",
            success: function(xml) {
                this.xml=xml;
                $(window).trigger("canUseXML");
                var docLength = $(xml).find('Question').length + 1;
                alert("this really is an '" + this.xml + "' and the actual doclength is: " + docLength)//This is the first alert I mention.         
            } //close success           
        });//close AJAX     

        alert("yes! this is still a: " +this.xml) //This is the second alert I mention.
    },

If it all ran as expected, both alerts would result in an 'object XMLDocument' (a variable declared elsewhere in this line: this.xml = null;). The first runs as expected. However, the second, outside of that function, returns value "null". Why?

Thanks, Elliot Bonneville

P.S. I've been stuck on the seemingly simple question of passing variables between functions for a week.

Upvotes: 1

Views: 154

Answers (4)

Residuum
Residuum

Reputation: 12064

You have two problems:

  1. Scoping: this inside the callback is not your object with GetXML as a member. Use something like me = this; in the constructor of your object and then use me instead of this to explicitely set the value.

  2. You callback function waits for a success of your Ajax request, but the rest of the script is going on, which is the purpose of callbacks. So, the Ajax request is made, and then you do alert("yes! this is still a: " +this.xml), while the callback has not yet been executed.

Upvotes: 1

stewe
stewe

Reputation: 42632

In JavaScript "this" always refers to the “owner” of the function executed, or rather, to the object that a function is a method of. So your first and second "this" does not refer to the same thing.

Assuming that the "success" function executes before the second alert (which it probably doesn't). You could do something like this:

GetXML: function() {
 var that=this;
.
.

and then use "that" instead of "this".

Upvotes: 2

m4tt1mus
m4tt1mus

Reputation: 1641

Scoping. Once you travel outside of anonymous function(xml) this.xml no longer exists.

Upvotes: 1

Kerry Jones
Kerry Jones

Reputation: 21838

This is probably happening because ajax takes time to process. Javascript doesn't wait for one request before executing the next command, so while AJAX is being called, its trying to figure out what happened to this.xml.

Upvotes: 0

Related Questions