0

I'm getting the correct stuff in done but the assignment to a variable with an wider scope doesn't work. It worked for e.g. $.each(...) so I assumed, incorrectly, that it'd work here too.

var outee = null;
$.ajax({
  url: "http://...",
  dataType: 'jsonp',
  ...
}).done(function (stuff) { 
  // works well
  displayThe(stuff);
  // works well (but targets probably a global outee)
  outee = stuff;
  displayThe(outee);
});
// fail due to outee being nada, nicht, zilch etc.
displayThe(outee);

How can I store stuff for usage outside the scope of the anonymous function in done method that obtained it?

Am I correct to assume that the assignment inside done refers to a global outee? One way to resolve my problem would be not to hide the global outee by the declaration n the method of a var-ed outsee, right? But that's a bad programming style to me. Comments?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 4
    It's not a scope problem. Assigning the value like you did is fine. The problem is that `displayThe(outee);` (in the last line) is called **before** the Ajax response was received, i.e. before the data as been set. Ajax is **asynchronous**. Maybe this helps you: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/. As long as you can ensure that the access to the global variable always occurs *after* the value was set, you are fine. – Felix Kling Jun 22 '13 at 09:42

1 Answers1

1

Yes, you are right you are assigning to a global variable in your .done, There's nothing wrong in that, the problem is that you are trying to use that global variable before your ajax call is completed (i.e before your .done is executed).

That is because of asynchronous behavior or ajax. One bad way to make it work is to make your ajax call synchronous with async:false

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • 1
    As you said, `async:false` is bad and even more so it does not work with JSONP (what the OP seems to use). – Felix Kling Jun 22 '13 at 09:46
  • OP **is** JSONP'ing so he can't (and doesn't want to of badness considerations) to set it on asynchronous. Now that I think about it, I realize that what I want is an **asynchronous** call that is guaranteed to be **performed before** other stuff. I know, I know - I'm being sarcastic over my own brain-cheeze-cutting. – Konrad Viltersten Jun 22 '13 at 09:56