0
(function () {
    var id="test";
    $.ajax({
       context: this,
       url : "http://weather.yahooapis.com/forecastrss",
       success : function(data){
            this.id = "was test";
       }
    });
    console.log(id);
})();

The previous question wasn't clear enough so hear is what the question really is. When I'm doing console.log(id) it doesn't show the changed value. What I'd like to get is the changed value of id. How can I achieve this, I've tried all the solutions in the comments and the given answers as well but none has worked for me?

A jsFiddle will be highly appreciated.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Adnan Ahmed
  • 684
  • 8
  • 15

4 Answers4

1

In getTodayCats:

var self = this;

And then when need to access ids, you should get it like this:

self.ids

The usage of the self, this pattern is made in this case since you need to access a property of this in an asynchronous callback handler(ajax success). Handlers for asynchronous callbacks are called without the original this object, so this is used to utilize the function's closure to pass in the original.

In case of the jQuery's ajax method, you could also use the context option to pass in the this object which will be used for its callback handlers. It's up to you on whether you use it. I personally prefer not to, since this isn't an option for other async handlers such as in the case of timeout and intervals, and I prefer to keep it consistent.

Naor Biton
  • 952
  • 9
  • 14
0
 $.ajax({
     url: "http://localhost/woodenspoon/getTodaysCats.php",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     responseType: "json",
     context: this,
     success: function (data) {

         this.ids = "ok";

     }
 });
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

Access "ids" this way-

getTodaysCats: function () {

    var args = Array.prototype.slice.call( WinJS.UI.Pages.define.arguments);
    var ids = args[1].ids;
    $.ajax({               
        ...
        , success: function (data) {
            var arr = new Array(1,2,3,4,5);
            foreach(var num in arr)
                ids += "ok";    
        }
    });

    return ids;
}
abipc
  • 997
  • 2
  • 13
  • 35
-1

try using something like this...

${variable}

Mark McK
  • 84
  • 2
  • 2
  • 12