$.get is asynchronous, meaning the call to $.get returns immediately, even
before the callback has happened. To answer your specific question, setting
a variable who's scope is outside the callback is as easy as defining the
variable outside the callback:

var foo;
$.get(..., function() { foo = ...; });

But to address the actual problem that you're having, here are the order in
which your functions are being executed:

Enter isTracked
Enter $.get
Leave $.get
Leave isTracked
Enter callback
Leave callback

So you see, by the time isTracked returns, your callback hasn't executed
yet, which is why you see null the first time, and the first value the
second time. To do what you want to do, you need to step back a level.
Presumably, you do something with the return value from isTracked, so you
don't want isTracked to return until it has said value. Say you have:

var tracked = isTracked(code);
// do something with tracked.

To do what you want, you need to pass a callback to isTracked that will get
called once the data is available. In your case, you could just pass the
callback along to $.get. So your setup might look something like:

function isTracked(personcode, callback) {
  $.get('trackstudent/istracked.php', {'personcode': personcode}, callback);
}

isTracked(code, function(tracked) {
  // do something with tracked, exactly as you would have done above.
});

This is just part of how JavaScript works, and part of why anonymous
functions are so prevalent.

Hope it helps.

--Erik


On 9/27/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>
> Im trying to set somehow variable inside of $.get callback and get
> outside this callback.
> Im doing it in this way (because I dont know any other way):
>
> function isTracked(personcode)
> {
> ret='false';
>
> // it should return string 'true' or 'false'
> $.get('trackstudent/istracked.php',{'personcode': personcode},
> function(data) {
>
> //because I dont know how to set variable inside of callback and get
> outside
> if ($('span.tempvar').length==0)
>    $('body').append('<span class="tempvar" style="display: none">'+data
> +'</span>');
> else
>     $('span.tempvar').html(data);
>
> // now I should have at the end of <body> a new element <span>
> alert('1: '+$('span.tempvar').html());
>
> });
> //get variable outside $.get callback
> ret=$('span.tempvar').html();
> alert('2: '+ret);
>
> //return ret; //ret have proper value
> }
>
> .......
> when I run this function first time I have two alert messages (data in
> $.get is 'true'):
> first: "1: true"
> second: "2: null"
> //second should be: "2: true";
>
> when I run second time I have (data in $.get is 'false'):
> first: "1: false"
> second: "2: true" //old value! (dont know why!)
> //second should be false;
>
> When Im checking genereted by javascript source code I see my <span>
>
> How it is possible?!
>
> or maybe you have another solution how to set variable inside of $.get
> callback and get outside
>
> TIA
> Michael
>
>

Reply via email to